Skip to content

Instantly share code, notes, and snippets.

@iso2022jp
Created December 15, 2020 10:36
Show Gist options
  • Save iso2022jp/c2aeb40dfd43d2871f1fb592a9bffac1 to your computer and use it in GitHub Desktop.
Save iso2022jp/c2aeb40dfd43d2871f1fb592a9bffac1 to your computer and use it in GitHub Desktop.
TextDecoder を使って無理矢理 Windows-31J の Encoder を作る
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