Skip to content

Instantly share code, notes, and snippets.

@sidedwards
Created October 26, 2021 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidedwards/b03f5c653d27109a04025fea836d360b to your computer and use it in GitHub Desktop.
Save sidedwards/b03f5c653d27109a04025fea836d360b to your computer and use it in GitHub Desktop.
Pseudo-translate your JSON files!
import { parse } from "https://deno.land/std@0.113.0/flags/mod.ts"
import { v4 } from "https://deno.land/std@0.113.0/uuid/mod.ts";
const ARGS = parse(Deno.args)
const PATH = ARGS.path ?? null
const NODE = ARGS.node ?? 'content'
const FORMAT = ARGS.format ?? 'json'
const TYPE = ARGS.type ?? 'pseudo'
const DIRECTORY = PATH ?? Deno.cwd()+'/'
const CHARS = {
'a':'ä', 'c':'ç', 'i':'ï', 'C':'Ç',
'A':'Ä', 'e':'é', 'E':'É', 'D':'Ð',
'o':'ö', 'O':'Ö', 'u':'ü', 'U':'Ü',
'n':'ñ', 'r':'ř', 'Y':'Ý', 'w':'ω',
'N':'Ñ'
}
const DATE = new Date();
const TIMESTAMP = DATE.getFullYear() + "-" + ("0" + (DATE.getMonth() + 1)).slice(-2) + "-" + ("0" + DATE.getDate()).slice(-2) + " " + DATE.getHours() + ":" + DATE.getMinutes()
const _replaceChars = (str: string) => {
for (let [key, value] of Object.entries(CHARS)) {
str = str.replace(
RegExp(key, "g"),
value
)
}
return str
}
const _processValue = (str: string) => {
const words = str.replace(/({{)\s+(\S+)\s+(}})/g, "$1﹏$2﹏$3").split(/ +/g)
const newWords = words.map(word => {
const re = new RegExp(/{{.*}}/)
if ( re.test(word) ) {
return word.replace(/﹏/g, ' ')
} else {
return _replaceChars(word)
}
})
return newWords.join(' ')
}
const _wrapSentence = (str: string) => {
return `«${str}»`
}
async function main() {
for await (const fileOrFolder of Deno.readDir(DIRECTORY)) {
if (fileOrFolder.isFile && fileOrFolder.name.endsWith(`.${FORMAT}`)) {
const filePath = `${DIRECTORY}${fileOrFolder.name}`
const data = JSON.parse(await Deno.readTextFile(filePath))
for (const property in data[NODE]) {
if (property === 'slug') {
continue;
}
const source = data[NODE][property]
let target = source
switch (TYPE) {
case 'pseudo':
target = _wrapSentence(_processValue(source))
break;
case 'timestamp':
target = `(${TIMESTAMP}): ${data[NODE][property]}`
break;
case 'unique':
target = `(${v4.generate().substring(0, 8)}): ${data[NODE][property]}`
break;
default:
break;
}
data[NODE][property] = target
console.log("target: " +target)
}
await Deno.writeTextFile(filePath, JSON.stringify(data))
console.log(`file: ${DIRECTORY}${fileOrFolder.name}`)
}
}
return
}
export default main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment