// register compare operator
// e.g. {{#when <operand1> 'eq' <operand2>}} {{/when}}
// {{#when var1 'eq' var2}}equal{{else when var1 'gt' var2}}gt{{else}}lt{{/when}}
Handlebars.registerHelper("when", (operand_1, operator, operand_2, options) => {
let operators = {
'eq': (l, r) => l == r,
'==': (l, r) => l == r,
'===': (l, r) => l === r,
'noteq': (l, r) => l != r,
'!=': (l, r) => l != r,
'!==': (l, r) => l !== r,
'gt': (l, r) => (+l) > (+r),
'>': (l, r) => (+l) > (+r),
'gteq': (l, r) => ((+l) > (+r)) || (l == r),
'>=': (l, r) => ((+l) > (+r)) || (l == r),
'lt': (l, r) => (+l) < (+r),
'<': (l, r) => (+l) < (+r),
'lteq': (l, r) => ((+l) < (+r)) || (l == r),
'<=': (l, r) => ((+l) < (+r)) || (l == r),
'or': (l, r) => l || r,
'||': (l, r) => l || r,
'and': (l, r) => l && r,
'&&': (l, r) => l && r,
'mod': (l, r) => (l % r) === 0,
'%': (l, r) => (l % r) === 0
};
let result = operators[operator](operand_1, operand_2);
if (result) return options.fn(this);
return options.inverse(this);
});
// register replace operator
// e. g. {{#replace <find> <replace>}}{{string}}{{/replace}}
Handlebars.registerHelper('replace', function( find, replace, options) {
let string = options.fn(this);
return string.replaceAll( find, replace );
});
// register split operator
// {{#split <find> <index>}}<string>{{/split}}
// e. g. {{#split "/" -1}}https://test.com/target{{/split}} => target
Handlebars.registerHelper('split', function( find, index, options) {
let string = options.fn(this);
let result = string.split( find );
if (index < 0) return result[result.length + index];
else return result[index];
});
// register split interator
// {{#each_split <string> <find>}}...{{/each_split}}
// e. g. {{#each_split "https://test.com/target" "/"}}{{.}},{{/each_split}} => https:,,test.com,target,
Handlebars.registerHelper('each_split', function( string, find, options) {
let data = string.split(find);
let result = '';
data.forEach((item) => {
result += options.fn(item);
});
return result;
});
// register substring operator
// {{#substring start end}}<string>{{/substring}}
// e. g. {{#substring 0 4}}My-test-string{{/substring}} => My-t
// e. g. {{#substring -2 ""}}My-test-string{{/substring}} => ng
// e. g. {{#substring 0 -2}}My-test-string{{/substring}} => My-test-stri
Handlebars.registerHelper('substring', function( start, end, options) {
let string = options.fn(this);
let result = "";
if (end === "") result = string.slice( start);
else result = string.slice( start, end );
return result;
});