Created
September 7, 2022 11:56
-
-
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
This file contains hidden or 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
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