Skip to content

Commit

Permalink
Added better flattening algorithm and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
rangle-mobinni committed Mar 20, 2019
1 parent d9838a0 commit d63d2e4
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 25 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ example execution
translate ./example/en.json -i nl -k some_key -r "{{([^}]+?)}}"
```

In the above example following string will be translated:
```
"n2": "with {{some}} regexs in it"
```
to dutch
```
"n2": "met {{some}} regexs in het"
```

As you can see the regex allows interpolations to stay intact while translating.

**Web Usage**
```javascript
import translate from "i18n-json-tool";
Expand Down
4 changes: 2 additions & 2 deletions example/nl.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"hello": "Hallo, ik ben een vertaling tool",
"cool": "Ik kan omgaan met {{complexe}} reguliere expressie gevallen",
"cool": "Ik kan omgaan met {{complex}} reguliere expressie gevallen",
"nested": {
"n1": "Ik kan zelfs geneste strings",
"n2": "met {{aantal}} regexs in het"
"n2": "met {{some}} regexs in het"
},
"months": {
"full": {
Expand Down
42 changes: 19 additions & 23 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,30 @@
const { keys, path: pathOf } = require("ramda");
const { chain, type, toPairs, fromPairs, map, keys } = require("ramda");

const { isoCodes } = require("./iso-codes");

module.exports.verifyISOCode = code =>
!!isoCodes.find(iso => iso.code === code);

const verify = obj => typeof obj === "string" || typeof obj === "number";

module.exports.traverse = obj => {
const results = [];

function loopKeys(obj, prevPath = []) {
const objKeys = keys(obj);
return objKeys.map(k => {
let path = [];
if (!verify(obj[k])) {
if (prevPath) path = prevPath;
path.push(k);
loopKeys(obj[k], path);
// https://github.com/ramda/ramda/wiki/Cookbook#flatten-a-nested-object-into-dot-separated-key--value-pairs
const flattenObj = obj => {
const go = obj_ =>
chain(([k, v]) => {
if (type(v) === "Object" || type(v) === "Array") {
return map(([k_, v_]) => [`${k}.${k_}`, v_], go(v));
} else {
results.push({
path: [...prevPath, k],
phrase: obj[k]
});
return [[k, v]];
}
path.pop();
});
}
loopKeys(obj);
return results;
}, toPairs(obj_));

return fromPairs(go(obj));
};

module.exports.traverse = obj => {
const flattened = flattenObj(obj);
return keys(flattened).map(k => ({
path: k.split("."),
phrase: flattened[k]
}));
};

module.exports.revertInterpolations = placeholder => ({
Expand Down

0 comments on commit d63d2e4

Please sign in to comment.