Skip to content

Instantly share code, notes, and snippets.

@cj1128
Created May 22, 2018 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cj1128/33ede5fd92b8ab191ff8c286fbfa76b2 to your computer and use it in GitHub Desktop.
Save cj1128/33ede5fd92b8ab191ff8c286fbfa76b2 to your computer and use it in GitHub Desktop.
Encode string use core value word
const chars = [
"富强",
"民主",
"文明",
"和谐",
"爱国",
"敬业",
"诚信",
"友善",
"自由",
"平等",
"公正",
"法制",
]
// point is a base-12 number string
const encodePoint = point => point
.split("")
.map(c => chars[parseInt(c, 12)])
.join("")
const encode = str => str
.split("")
.map(s => s.charCodeAt(0).toString(12))
.map(n => n.length + n)
.map(encodePoint)
.join("")
const decodePoint = codes => {
const s = codes.map(c => "0123456789ab"[c])
return String.fromCharCode(parseInt(s.join(""), 12))
}
const decode = str => {
const chunks = []
for(let i = 0; i < str.length; i += 2) {
chunks.push(str.slice(i, i + 2))
}
const codes = chunks.map(c => chars.indexOf(c))
let r = ""
for(let i = 0; i < codes.length;) {
const n = codes[i]
r += decodePoint(codes.slice(i + 1, i + n + 1))
i += n + 1
}
return r
}
console.log(encode("hello world"))
console.log(decode("文明自由自由文明自由敬业文明平等富强文明平等富强文明平等和谐文明文明自由文明平等法制文明平等和谐文明平等诚信文明平等富强文明自由爱国"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment