All files / src/helpers math.ts

100% Statements 18/18
100% Branches 11/11
100% Functions 2/2
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 312x   2x 29x 35x 35x   35x 3x     32x   10x   3x   7x   5x   2x   4x 2x   1x        
import { HandlebarsHelper, HelperConstructorBlock } from "./helper";
 
export const mathHelper: HelperConstructorBlock = ctx => {
    return new HandlebarsHelper("math", (rawV1, operator, rawV2): number => {
        const v1 = Number.parseFloat(rawV1);
        const v2 = Number.parseFloat(rawV2);
 
        if (Number.isNaN(v1) || Number.isNaN(v2)) {
            throw new Error(`Can't convert "${rawV1}" and "${rawV2}" to numbers while using math`);
        }
 
        switch (operator) {
            case "+":
                return v1 + v2;
            case "-":
                return v1 - v2;
            case "*":
                return v1 * v2;
            case "/":
                return v1 / v2;
            case "**":
                return v1 ** v2;
            case "%":
                if (!v2) throw new Error("% operator used with 0");
                return v1 % v2;
            default:
                throw new Error(`Invalid operator used with math: ${operator}`);
        }
    });
};