UNPKG

math-array

Version:

Math utility to calculate with two arrays.

90 lines (62 loc) 1.83 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const error = (message // code ) => { const e = new Error(message); // if (code) { // e.code = code // } throw e; }; const manipulate2Array = (a, b, mutator) => { if (a.length !== b.length) { error('the length of arrays not match'); } return a.map((x, i) => mutator(x, b[i])); }; const manipulateArray = (a, b, mutator) => { return a.map(x => mutator(x, b)); }; const isArray = (a, b) => [a, b].map(Array.isArray); const cleanArray = array => { array.forEach((item, i) => { if (item !== item) { delete array[i]; } }); }; const orderUnaware = (a, b, mutator, mutatorReverse, ensureNumber) => { const [A, B] = isArray(a, b); const ret = A ? B ? manipulate2Array(a, b, mutator) : manipulateArray(a, b, mutator) : B ? manipulateArray(b, a, mutatorReverse) : error('at least one array is required'); if (ensureNumber) { cleanArray(ret); } return ret; }; const orderAware = (a, b, mutator, ensureNumber) => { const [A, B] = isArray(a, b); const ret = A ? B ? manipulate2Array(a, b, mutator) : manipulateArray(a, b, mutator) : error('the first argument must be an array'); if (ensureNumber) { cleanArray(ret); } return ret; }; const add = (a, b) => a + b; const addReverse = (a, b) => b + a; var add$1 = ((a, b, n) => orderUnaware(a, b, add, addReverse, n)); const sub = (a, b) => a - b; var sub$1 = ((a, b, n) => orderAware(a, b, sub, n)); const mul = (a, b) => a * b; var mul$1 = ((a, b, n) => orderUnaware(a, b, mul, mul, n)); const div = (a, b) => { if (b === 0) { error('divide by zero'); } return a / b; }; var div$1 = ((a, b, n) => orderAware(a, b, div, n)); exports.add = add$1; exports.sub = sub$1; exports.mul = mul$1; exports.div = div$1;