Last active
August 28, 2016 16:56
-
-
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
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
// 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