3 ms·
This is a neat trick, but the example code (after fixing a typo, "decodeNonNegatve" to "decodeNonNegative") doesn't sort correctly: ["-10", "-11", "0", "1",
by lokedhs 9y ago
This is a neat trick, but the example code (after fixing a typo, "decodeNonNegatve" to "decodeNonNegative") doesn't sort correctly:
["-10", "-11", "0", "1", "-1", "-2", "10", "11", "110"].map(encodeLong).sort().map(decodeLong)
Results in:
["0", "1", "10", "11", "110", "-11", "-10", "-2", "-1"]
- rockostrich 9y agoThe author used `-` as the sorting character for negatives instead of `!` as stated in the article. If you change his functions to use `!` for encoding negatives then it correctly sorts. function encodeLong(s) { if (s[0] !== '-') { return encodeNonNegative(s, ' '); } return '!' + translate(encodeNonNegative(s.slice(1), ' ')); } function decodeLong(s) { if (s[0] !== "!") { return decodeNonNegative(s); } return '-' + decodeNonNegative(translate(s.slice(1))); }