From 0e923aa4b4a0f3c9d0ee356c03c18e443d454ba1 Mon Sep 17 00:00:00 2001 From: Caleb Fontenot Date: Sun, 30 Apr 2023 18:33:24 -0500 Subject: [PATCH] Let's try mozilla's fixedCharAt function --- commands/drawDesign.cjs | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/commands/drawDesign.cjs b/commands/drawDesign.cjs index ba61542..d8d7417 100644 --- a/commands/drawDesign.cjs +++ b/commands/drawDesign.cjs @@ -262,14 +262,14 @@ function design5(input) { if (dist > radius - 1 && dist < radius + 1) { //&& dist > radius - 1 lineHasInput = true; - outputLine += "​" + input.charCodeAt(charIterate(input)); //zero-width space + outputLine += "​" + input.fixedCharAt(charIterate(input)); //zero-width space } else { outputLine += " "; } } } else { lineHasInput = true; - outputLine += input.charCodeAt(charIterate(input)) + space + input + space + spaceOffset + input.charCodeAt(charIterate(input)); + outputLine += input.fixedCharAt(charIterate(input)) + space + input + space + spaceOffset + input.fixedCharAt(charIterate(input)); } //console.log(i, j, outputLine); @@ -280,5 +280,38 @@ function design5(input) { } return outputString; } + +// Code from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt + +function fixedCharAt(str, idx) { + str = String(str); + + const surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + while (surrogatePairs.exec(str) !== null) { + const lastIdx = surrogatePairs.lastIndex; + if (lastIdx - 2 < idx) { + idx++; + } else { + break; + } + } + + if (idx >= str.length || idx < 0) { + return ""; + } + + let ret = str.charAt(idx); + + if ( + /[\uD800-\uDBFF]/.test(ret) && + /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1)) + ) { + // Go one further, since one of the "characters" is part of a surrogate pair + ret += str.charAt(idx + 1); + } + return ret; + } + + //console.log(design4("super long test string super long test string")); //"super long test string super long test string" \ No newline at end of file