Created
March 2, 2022 21:09
-
-
Save Yemolai/0e79234dcc1ac6dfbd413f8087c7bbd3 to your computer and use it in GitHub Desktop.
This is a Sanity check javascript script to compare values when you think you are going crazy but you just want to confirm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Compare and write where the difference between strings is | |
* @param {String} a string to compare | |
* @param {String} b string to compare | |
* @returns {String} comparison | |
*/ | |
function compareStrings(a: string, b: string): string { | |
if (a.split('').every((c, n) => b.charCodeAt(n) == c.charCodeAt(0))) { | |
return `\x1b[32m${a} == ${b}\x1b[0m`; | |
} | |
const [bigger, smaller] = a.length < b.length ? [b, a] : [a, b]; | |
const diff = bigger.split('').map((char, idx) => ({ | |
idx, | |
bigger: char, | |
smaller: smaller[idx] ?? '\x1b[4m_', | |
diff: char.charCodeAt(0) != smaller.charCodeAt(idx), | |
})); | |
const { acc: biggerDiff } = diff.reduce( | |
({ acc, lastDiff }, { bigger: char, diff }) => { | |
const part = | |
(lastDiff === diff ? '' : diff ? '\x1b[31m' : '\x1b[32m') + char; | |
return { | |
acc: `${acc}${part}`, | |
lastDiff: diff, | |
}; | |
}, | |
{ acc: '', lastDiff: null } as { acc: string; lastDiff: boolean | null } | |
); | |
const { acc: smallerDiff } = diff.reduce( | |
({ acc, lastDiff }, { smaller: char, diff }) => { | |
const part = | |
(lastDiff === diff ? '' : diff ? '\x1b[31m' : '\x1b[32m') + char; | |
return { | |
acc: `${acc}${part}`, | |
lastDiff: diff, | |
}; | |
}, | |
{ acc: '', lastDiff: null } as { acc: string; lastDiff: boolean | null } | |
); | |
return `${biggerDiff}\x1b[31m !== ${smallerDiff}\x1b[0m`; | |
} | |
console.log(compareStrings('Gabriel Rodrigues', 'Gabriel Rodrigues')); | |
console.log(compareStrings('1234567890', '1234567890')); | |
console.log(compareStrings('123456789', '8761230897')); | |
console.log(compareStrings('Gabriel Rodrigues', 'Gabrie1 Rodrigue5')); | |
console.log(compareStrings('SUPER_LARGE_STRING_HERE', 'tiny')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment