Browse Source

feat: add `multiply`, `increment`, `divide`, and `subtract` function

Ahmad Kholid 3 years ago
parent
commit
7542258815
1 changed files with 22 additions and 1 deletions
  1. 22 1
      src/utils/referenceData/mustacheReplacer.js

+ 22 - 1
src/utils/referenceData/mustacheReplacer.js

@@ -7,6 +7,7 @@ const refKeys = {
   dataColumn: 'table',
   dataColumns: 'table',
 };
+const isAllNums = (...args) => args.every((arg) => !Number.isNaN(+arg));
 
 /* eslint-disable prefer-destructuring, no-useless-escape */
 export const functions = {
@@ -48,6 +49,26 @@ export const functions = {
 
     return value.slice(startIndex, endIndex);
   },
+  multiply(value, multiplyBy) {
+    if (!isAllNums(value, multiplyBy)) return value;
+
+    return +value * +multiplyBy;
+  },
+  increment(value, incrementBy) {
+    if (!isAllNums(value, incrementBy)) return value;
+
+    return +value + +incrementBy;
+  },
+  divide(value, divideBy) {
+    if (!isAllNums(value, divideBy)) return value;
+
+    return +value / +divideBy;
+  },
+  subtract(value, subtractBy) {
+    if (!isAllNums(value, subtractBy)) return value;
+
+    return +value - +subtractBy;
+  },
   randData(str) {
     const getRand = (data) => data[Math.floor(Math.random() * data.length)];
     const lowercase = 'abcdefghijklmnopqrstuvwxyz';
@@ -175,7 +196,7 @@ function replacer(str, { regex, tagLen, modifyPath, data }) {
     }
 
     result = typeof result === 'string' ? result : JSON.stringify(result);
-    replaceResult.list[match] = result.slice(0, 512);
+    replaceResult.list[match] = result?.slice(0, 512) ?? result;
 
     return result;
   });