i18n-llm-translate
Version:
Automatically translates namespace-based JSON translation files across multiple languages from any source language
101 lines (100 loc) • 2.31 kB
JavaScript
;
// TODO
// TODO
// TODO
// TODO
// TODO
// TODO
// TODO
// TODO
// TODO
// TODO
Object.defineProperty(exports, "__esModule", { value: true });
exports.walkTree = walkTree;
function getType(val) {
if (val === null || val === undefined)
return 'null';
if (Array.isArray(val))
return 'array';
if (typeof val === 'object')
return 'leaf';
return 'primitive';
}
function walkTree(...args) {
if (args.length === 2) {
const [tree, walker] = args;
const result = {};
for (const key in tree) {
const val = tree[key];
const type = getType(val);
result[key] =
type === 'leaf'
? walkTree(val, walker)
: walker(val, type);
}
return result;
}
if (args.length === 3) {
const [a, b, walker] = args;
const result = {};
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
for (const key of keys) {
const aVal = a[key];
const bVal = b[key];
const aType = getType(aVal);
const bType = getType(bVal);
result[key] =
aType === 'leaf' && bType === 'leaf'
? walkTree(aVal, bVal, walker)
: walker(aVal, aType, bVal, bType);
}
return result;
}
throw new Error("Invalid arguments to walkTree");
}
const a = {
title: "Hello",
count: 2,
nested: {
value: 5
}
};
const b = {
title: "Hi",
count: 3,
nested: {
value: 5,
other: "x"
}
};
const diffTree = walkTree(a, b, (a, aType, b, bType) => {
return `${aType} ${bType}`;
});
// Typ: TranslationLeaf<boolean>
console.log(diffTree);
const aa = {
title: "Hello",
count: 1,
nested: {
label: "Name",
items: ["a", "b"]
},
ignored: "will be removed"
};
const bb = {
title: "Hello",
count: 2,
nested: {
label: "Name",
items: ["a", "c"]
},
extra: "also removed"
};
const keepSame = (a, aType, b, bType) => {
return a === b ? a : undefined;
};
const common = walkTree(aa, bb, keepSame);
walkTree(aa, (leaf, type) => {
return type;
});
console.log(JSON.stringify(common, null, 2));