Created
December 15, 2020 10:36
-
-
Save iso2022jp/c2aeb40dfd43d2871f1fb592a9bffac1 to your computer and use it in GitHub Desktop.
TextDecoder を使って無理矢理 Windows-31J の Encoder を作る
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 encodeWindows31J = text => { | |
const range = (from, to) => [...Array(to - from + 1).keys()].map(b => b + from) | |
const islead = b => (b >= 0x81 && b <= 0x9F) || (b >= 0xe0 && b <= 0xef) | |
const follows = [...range(0x40, 0x7e), ...range(0x80, 0xfc)] | |
const decoder = new TextDecoder('Windows-31J') | |
const sbmap = b => ({ [decoder.decode(new Uint8Array([b]))]: [b] }) | |
const dbmap = l => follows.reduce((mapping, f) => ({ ...mapping, [decoder.decode(new Uint8Array([l, f]))]: [l, f] }), {}) | |
const mapping = [...Array(256).keys()].reduce((mapping, b) => ({ ...mapping, ...islead(b) ? dbmap(b) : sbmap(b) }), {}) | |
return text.split('').reduce((bytes, c) => mapping[c] ? [...bytes, ...mapping[c]] : bytes, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment