Last active
September 14, 2023 22:41
-
-
Save MarkTiedemann/88b18afe54ca90060873d7ec1bbd78db to your computer and use it in GitHub Desktop.
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
// Ported from https://github.com/deoxxa/proquint | |
const encodeConsonants = "bdfghjklmnprstvz".split(""); | |
const encodeVowels = "aiou".split(""); | |
const decodeConsonants = Object.fromEntries(encodeConsonants.map((x, i) => [x, i])); | |
const decodeVowels = Object.fromEntries(encodeVowels.map((x, i) => [x, i])); | |
export function encode(array: Uint16Array) { | |
const view = new DataView(array.buffer); | |
const bits = []; | |
for (let i = 0; i < view.byteLength / 2; i++) { | |
const n = view.getUint16(i * 2); | |
const c1 = n & 0x0f; | |
const v1 = (n >> 4) & 0x03; | |
const c2 = (n >> 6) & 0x0f; | |
const v2 = (n >> 10) & 0x03; | |
const c3 = (n >> 12) & 0x0f; | |
bits.push( | |
encodeConsonants[c1] + | |
encodeVowels[v1] + | |
encodeConsonants[c2] + | |
encodeVowels[v2] + | |
encodeConsonants[c3] | |
); | |
} | |
return bits.join("-"); | |
} | |
export function decode(string: string) { | |
const bits = string.split("-"); | |
const array = new Uint16Array(bits.length); | |
const view = new DataView(array.buffer); | |
for (let i = 0; i < bits.length; i++) { | |
view.setUint16( | |
i * 2, | |
decodeConsonants[bits[i][0]] + | |
(decodeVowels[bits[i][1]] << 4) + | |
(decodeConsonants[bits[i][2]] << 6) + | |
(decodeVowels[bits[i][3]] << 10) + | |
(decodeConsonants[bits[i][4]] << 12) | |
); | |
} | |
return array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment