-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (41 loc) · 1.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/***************************************************************
* node/context/interpolate.js
*
* Copyright (C) Lolocodo AB - All rights reserved
***************************************************************/
const { get, isArray, reduce } = require('lodash');
const interpolate = (ctx, params) => {
return deepMap(params, val => interpolateOne(ctx, val));
};
const allRE = /{[^{}]*}/g;
const oneRE = /{([^{}]*)}/;
const interpolateOne = (ctx, str) => {
if (typeof str !== 'string') return str;
// debugging
if (str === '{}') return ctx;
const vars = str.match(allRE);
const processOne = str => {
const [, path] = str.match(oneRE);
return get(ctx, path, `{${path}}`);
};
// no variable expressions found
if (!vars) return str;
// return literal
if (vars[0] === str) return processOne(str);
// build string
return vars.reduce((memo, v) => {
memo = memo.replace(v, processOne(v));
return memo;
}, str);
};
const deepMap = (obj, fn) => {
if (isArray(obj)) return obj.map(i => deepMap(i, fn));
if (typeof obj !== 'object') return fn(obj);
return reduce(obj, (memo, v, k) => {
memo[k] = typeof v === 'object' ?
deepMap(v, fn) :
fn(v, k, obj);
return memo;
}, {});
};
module.exports = interpolate;