mustache_templates-8.x-1.0-beta4/js/magic/condition.js
js/magic/condition.js
/**
* @file
* Magic conditions for Mustache templates.
*/
(function (sync) {
var subset = sync.___internals.subset;
var isEmpty = sync.___internals.isEmpty;
var available = {empty: 0, numeric: 0, equals: 1, greaterthan: 1, biggerthan: 1, lessthan: 1, smallerthan: 1, atleast: 1, atmost: 1};
var evaluate = function(condition, actual, expected) {
if (actual === false) {
return condition === 'empty';
}
if (!condition || (available[condition] && typeof expected === 'undefined')) {
return false;
}
if (['defined', 'empty', 'numeric', 'equals'].indexOf(condition) < 0) {
if (actual === null || expected === null) {
return false;
}
if (typeof actual === 'object') {
actual = Object.keys(actual).length;
}
if (typeof expected === 'object') {
expected = Object.keys(expected).length;
}
if (isNaN(actual) || isNaN(expected) || typeof actual === 'boolean' || typeof expected === 'boolean' || (typeof actual === 'string' && isNaN(parseFloat(actual))) || (typeof expected === 'string' && isNaN(parseFloat(expected)))) {
return false;
}
}
switch (condition) {
case 'defined':
return !(actual === null || typeof actual === 'undefined');
case 'empty':
return isEmpty(actual);
case 'numeric':
return typeof actual === 'string' ? !(isNaN(actual) || isNaN(parseFloat(actual))) : !(typeof actual === 'boolean' || isNaN(actual));
case 'equals':
if (typeof actual === 'object') {
actual = JSON.stringify(actual);
}
if (typeof expected === 'object') {
expected = JSON.stringify(expected);
}
return (new String(actual)).valueOf() === (new String(expected)).valueOf();
case 'biggerthan':
case 'greaterthan':
return actual > expected;
case 'smallerthan':
case 'lessthan':
return actual < expected;
case 'atleast':
return actual >= expected;
case 'atmost':
return actual <= expected;
}
return false;
};
var magicCondition = function (buffer, props) {
return new Proxy(buffer, Object.assign({
condition: null,
comparisonValue: null,
keys: [],
cloned: false,
get: function (buffer, property, receiver) {
if (!this.cloned) {
return magicCondition(buffer, {cloned: true})[property];
}
if (this.condition) {
if (available[this.condition]) {
if (property.toLowerCase(property.trim()) == 'previous') {
this.keys.unshift('previous');
this.comparisonValue = subset(buffer.data, this.keys);
this.keys.shift();
}
else {
this.comparisonValue = property;
}
}
return evaluate(this.condition, subset(buffer.data, this.keys), this.comparisonValue);
}
else if (available.hasOwnProperty(property)) {
this.condition = property;
if (!available[this.condition]) {
return evaluate(this.condition, subset(buffer.data, this.keys), this.comparisonValue);
}
return receiver;
}
this.keys.push(property);
return receiver;
},
has: function(target, prop) {
return true;
}
}, props));
};
sync.registry.magic.if = function (buffer) {
return magicCondition(buffer, {});
};
}(mustacheSync));
