-
Notifications
You must be signed in to change notification settings - Fork 1
/
placeholded.class.js
59 lines (48 loc) · 1.98 KB
/
placeholded.class.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
56
57
58
59
var _ = require("lodash");
//what you would call a 'template'
var Placeholded = function (strings, tokens, curried) {
this.strings = strings;
this.tokens = _.map(tokens, String);
};
Placeholded.prototype.stringValueJoin = function (values) {
//works as the _.zip correctly orders the values in front of their respective strings,
//then flatten falattens it out so now we have a big array of thing in order, ready to be joined.
//Compact is required because of unequal length of strings and values, zipping introduces some undefineds in the array.
return _.compact(_.flatten(_.zip(this.strings, values))).join("");
};
//considers the array as an object with number keys to achieve the mapping. So it unintentionally will convert a ${"length"} placeholder to length of the array.
Placeholded.prototype.mapTokensToValues = function (map) {
var values = [];
_.each(this.tokens, function(token, index) {
values[index] = map[token];
});
return values;
};
Placeholded.prototype.unprovidedTokens = function (map) {
var diff = _.difference(_.unique(this.tokens), _.keys(map));
return _.isEmpty(diff)? false : diff;
};
//returns a map object
Placeholded.prototype.parseInterpolateArguments = function () {
var args = Array.prototype.slice.call(arguments);
if(_.isArray(args[0])) {
//from array
return _.extend({}, args[0]);
} else if(_.isObject(args[0])) {
//already may be object
return args[0];
} else {
//from list of arguments
return _.extend({}, args);
}
};
Placeholded.prototype.interpolate = function () {
var map = this.parseInterpolateArguments.apply(this, arguments);
if(this.unprovidedTokens(map) !== false) {
var diff = this.unprovidedTokens(map);
throw new Error(`string-placehold: value-token mismatch. No values provided for ${diff.length} placeholders. offending tokens : ${diff.join(", ")}`);
}
var valuesInOrder = this.mapTokensToValues(map);
return this.stringValueJoin(valuesInOrder);
};
module.exports = Placeholded;