Last active
February 8, 2019 14:57
-
-
Save bruceCzK/c99dfba76265d09cfa3188ff9028dc9d to your computer and use it in GitHub Desktop.
Generate txt
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
const {set, get, chain, trim, last, unset} = require('lodash') | |
module.exports = function generateTxt(json, strings = []) { | |
for (const item of strings) { | |
const {original, translation, stage, key} = item | |
const text = `"${stage > 0 || translation ? translation : original}<!-${original}-!>` | |
.replace(/^""(.+)/g, '"$1') | |
.replace(/(.+)""$/g, '$1"') | |
let keyPath = key.split('|') | |
if (last(keyPath) === '__key__') { | |
// key now is like [monarch_names, 7, __key__] | |
const parentPath = keyPath.slice(0, -2) // to [monarch_names] | |
const index = parseInt(keyPath[keyPath.length - 2]) | |
const originalKeyName = chain(json).get(parentPath).keys().get(index).value() // get current key name with index | |
const value = get(json, [...parentPath, originalKeyName]) // get monarch_name odds like 20 or 0 | |
if (value === undefined) { | |
continue | |
} | |
unset(json, [...parentPath, originalKeyName]) // delete [monarch_names, "Karl #0 Theodor"] | |
// set key name as "卡尔 #0 西奥多", note that wrapping quote is essential | |
set(json, [...parentPath, `"${trim(translation || original, '"')}"`], value) | |
/* now the whole object is like | |
monarch_names: { | |
// "Karl #0 Theodor": "20" // this has been removed | |
"卡尔 #0 西奥多": "20", // we set this with above code | |
"Otto Heinrich #0": "20" // next loop will replace this | |
} | |
*/ | |
continue | |
} | |
set(json, keyPath, text) | |
} | |
let string = JSON.stringify(json, null, 4) | |
string = string.split('\n') | |
.slice(1, -1) | |
.map(line => line.replace(/^\s{4}/, '')).join('\n') | |
.replace(/\\"/g, '@@') // \" -> @@ | |
.replace(/#+(?=")/g, '') // remove # in key name | |
.replace(/"/g, '') // remove " | |
.replace(/: /g, ' = ') // : -> = | |
.replace(/@@/g, '"') // @@ -> " | |
.replace(/,$/gm, '') // remove trailing comma | |
.replace(/\[/g, '{') // [ -> { | |
.replace(/]/g, '}') // ] -> } | |
.replace(/^(\s*)=(\s?){/gm, '$1{') // remove empty key and = | |
.replace(/<!-/g, '" # ').replace(/-!>/g, '') // add original text | |
return string | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment