Skip to content

Instantly share code, notes, and snippets.

@gerrard00
Last active August 28, 2016 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerrard00/60047664796640bd1a88b964df5f6798 to your computer and use it in GitHub Desktop.
Save gerrard00/60047664796640bd1a88b964df5f6798 to your computer and use it in GitHub Desktop.
Sort an array of strings backwards in js...I don't know why
// an array of strings mangled with this function will sort
// backwards. You can then mangle them again after the sorting
// to get your original words. of course, you could just do sort().reverse(), but
// I was curious. So, completely useless.
const maxUnicodeValue = 0x10FFFF;
function invertString(input) {
let result = '';
for(let c of input) {
const oldCode = c.codePointAt(0);
const newCode = -(oldCode - maxUnicodeValue);
result += String.fromCodePoint(newCode);
};
return result;
}
// function dump(name, val) {
// console.log(`${name}: ${val}\t${val.toString(16)}`);
// }
let raw = [ "We", "walk", "the", "streets", "at", "night"];
console.log('\nBefore sorting.');
console.dir(raw);
raw.sort();
console.log('\nSorted normally.');
console.dir(raw);
let mangled = raw.map(x => invertString(x));
mangled.sort()
// unmangle them after sorting
let mangledUnmangled = mangled.map(x => invertString(x));
console.log('\nSorted while mangled');
console.dir(mangledUnmangled);
// or just
console.dir(raw.sort().reverse());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment