Skip to content

Instantly share code, notes, and snippets.

@sandgraham
Created December 17, 2021 20:55
Show Gist options
  • Save sandgraham/92628f512a7b6dbe18f0dada4b373e64 to your computer and use it in GitHub Desktop.
Save sandgraham/92628f512a7b6dbe18f0dada4b373e64 to your computer and use it in GitHub Desktop.
Find string which is lexically sorted mid point between two other strings
// Algorithm adapted from an amazing StackOverflow answer:
// https://stackoverflow.com/questions/38923376/return-a-new-string-that-sorts-between-two-given-strings/38927158#38927158
const A = 97;
const B = 98;
const Z = 122;
const START = A - 1;
const END = Z + 1;
function findLexicalMiddleString(prev: string, next: string) {
let p = START;
let n = END;
let pos = 0;
// find leftmost non-matching character
do {
p = pos < prev.length ? prev.charCodeAt(pos) : START;
n = pos < next.length ? next.charCodeAt(pos) : END;
pos += 1;
} while (p == n);
// copy identical part of string
let str = prev.slice(0, pos - 1);
if (p == START) {
// prev string equals beginning of next
// next character is 'a'
while (n == A) {
// get char from next
n = pos < next.length ? next.charCodeAt(pos++) : END;
// insert an 'a' to match the 'a'
str += "a";
}
// next character is 'b'
if (n == B) {
// insert an 'a' to match the 'b'
str += "a";
// set to end of alphabet
n = END;
}
} else if (p + 1 == n) {
// found consecutive characters
// insert character from prev
str += String.fromCharCode(p);
// set to end of alphabet
n = END;
// p='z'
while ((p = pos < prev.length ? prev.charCodeAt(pos++) : START) == Z) {
// insert 'z' to match 'z'
str += "z";
}
}
// append middle character
return str + String.fromCharCode(Math.ceil((p + n) / 2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment