Skip to content

Instantly share code, notes, and snippets.

@pouretrebelle
Created September 7, 2022 11:56
Show Gist options
  • Save pouretrebelle/aae8002e8c3f495cc059fcb9df7bc3d3 to your computer and use it in GitHub Desktop.
Save pouretrebelle/aae8002e8c3f495cc059fcb9df7bc3d3 to your computer and use it in GitHub Desktop.
Taking a long array of integers between -1 and 1, code golfing it into base 36 and then decoding it
const encodeNumbers = (array) => {
const chunk = (arr, len) => {
var chunks = [],
i = 0,
n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, i += len));
}
return chunks
}
return chunk(array.map(n => n+1), 33).map(num => parseInt(num.join``, 3).toString(36)).join`,`
}
const decodeFunc = `
(longN) =>
longN.split\`,\`
.map((n) => parseInt(n, 36).toString(3).split\`\`.map((n) => n - 1))
.flat();
`
const decodeNumbers = eval(decodeFunc)
script = `const decodeNumbers = ${decodeFunc};` + script
script = script.replaceAll(/Float32Array\((\[[\n -01,]+\])\)/gm, (_, match) => {
const array = eval(match)
if (array.join`` !== decodeNumbers(encodeNumbers(array)).join``) {
throw new Error(`Number encoding not matching`)
}
return `Float32Array(decodeNumbers("${encodeNumbers(array)}"))`
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment