@entestat/formula
Version:
fast excel formula parser
82 lines (69 loc) • 2.47 kB
JavaScript
const {FormulaHelpers} = require("../formulas/helpers");
const {LocalDate} = require("./LocalDate");
function addToDate(lDate, numOffset){
return (new LocalDate()).fromMoment(lDate.asMoment().add(numOffset, 'days'));
}
function subFromDate(lDate, numOffset){
return addToDate(lDate, -numOffset);
}
const DateHelper = {
isDate(val){
return val && val.constructor && val.constructor.name === "LocalDate";
},
isNullDate(val){
return val == null || val === "";
},
isNullableDate(val){
return val == null || val === "" || DateHelper.isDate(val);
},
dateCompareOp(value1, infix, value2){
const firstIsDate = DateHelper.isDate(value1);
const secondIsDate = DateHelper.isDate(value2);
const firstIsNull = DateHelper.isNullDate(value1);
const secondIsNull = DateHelper.isNullDate(value2);
if(firstIsNull || secondIsNull){
return false;
}
const first = value1.asMoment();
const second = value2.asMoment();
switch (infix) {
case '=':
return first.isSame(second);
case '>':
return first.after(second);
case '<':
return second.after(first);
case '<>':
return !first.isSame(second);
case '<=':
return first.isSame(second) || second.after(first);
case '>=':
return first.isSame(second) || first.after(second);
}
throw Error('Infix.compareOp: Should not reach here.');
},
dateOp(infix, value1, value2){
const firstIsDate = DateHelper.isDate(value1);
const secondIsDate = DateHelper.isDate(value2);
if(infix === "+"){
if(firstIsDate){
return addToDate(value1, FormulaHelpers.acceptNumber(value2));
} else {
if(!secondIsDate){
throw new Error(`Unrecognized date operation`);
}
return addToDate(value2, FormulaHelpers.acceptNumber(value1));
}
} else if(infix === "-"){
if(firstIsDate){
return subFromDate(value1, FormulaHelpers.acceptNumber(value2));
} else {
throw new Error(`Unrecognized date operation`);
}
}
throw new Error(`Unrecognized date operation`);
}
}
module.exports = {
DateHelper
};