1 | debug = require('debug')('christacheio');
|
2 | _ = require 'lodash'
|
3 | {deepGet,deepSet} = require 'lodash-deep'
|
4 | escapeStringRegexp = require 'escape-string-regexp'
|
5 |
|
6 | regexMatches = (regexString, string) ->
|
7 | regex = new RegExp regexString, 'g'
|
8 |
|
9 | matches = []
|
10 | while match = regex.exec string
|
11 | matches.push match[1]
|
12 | return matches;
|
13 |
|
14 | christacheio = (jsonString, obj, tags, transformation) ->
|
15 | tags ?= ['{{', '}}']
|
16 | transformation ?= (data) -> data
|
17 | regexStr = "#{tags[0]}(.*?)#{tags[1]}"
|
18 | map = {}
|
19 |
|
20 | newJsonString = _.clone jsonString
|
21 |
|
22 | _.each regexMatches(regexStr, jsonString), (key) ->
|
23 | map[key] = transformation deepGet(obj, key)
|
24 | map[key] ?= null
|
25 |
|
26 | _.each map, (value, key) ->
|
27 | escapedKey = escapeStringRegexp key
|
28 | regex = new RegExp tags[0] + escapedKey + tags[1], 'g'
|
29 | newJsonString = newJsonString.replace regex, map[key]
|
30 |
|
31 | return newJsonString
|
32 |
|
33 | module.exports = christacheio
|
34 |
|
35 |
|
36 | ###
|
37 | var _ = require('lodash');
|
38 | var debug = require('debug')('christacheio');
|
39 | var deepGet = require('lodash-deep').deepGet;
|
40 | var deepSet = require('lodash-deep').deepSet;
|
41 | var escapeStringRegexp = require('escape-string-regexp');
|
42 | //
|
43 | var christacheio = function(tags, jsonString, obj, transformation) {
|
44 | var regexStr, map, newJsonString;
|
45 | transformation = transformation || function(data) { return data; }
|
46 | tags = tags || ['{{', '}}'];
|
47 | regexStr = tags[0] + '(.*?)' + tags[1];
|
48 | map = {};
|
49 | newJsonString = _.clone(jsonString);
|
50 | //
|
51 | function regexMatches(regexString, string){
|
52 | var regex, matches, match;
|
53 | regex = new RegExp(regexString, 'g');
|
54 | matches = [];
|
55 | while(match = regex.exec(string)){
|
56 | matches.push(match[1]);
|
57 | }
|
58 | return matches;
|
59 | };
|
60 | //
|
61 | _.each(regexMatches(regexStr, jsonString), function(key) {
|
62 | var value = deepGet(obj, key);
|
63 | value = transformation(value);
|
64 | map[key] = value || null;
|
65 | });
|
66 | //
|
67 | _.each(map, function(value, key){
|
68 | var escapedKey = escapeStringRegexp(key);
|
69 | var regex = new RegExp(tags[0] + escapedKey + tags[1], 'g');
|
70 | newJsonString = newJsonString.replace(regex, map[key]);
|
71 | });
|
72 | //
|
73 | return newJsonString;
|
74 | }
|
75 | //
|
76 | module.exports = christacheio;
|
77 | ###
|