I have a 5 dimensional, multidimension array in JavaScript. I need to multiple each value by m
, but cap it at cap
. At present it is a 5 dimensional array, but I might need to add another dimension if I improve the functionality of the program at a later stage. So I would like to future proof my MultArrFunction
if possible.
Is there a better way of doing this? This looks so messy.
const MultArrFunction = (arr, m, cap) => {
return arr.map(v => v.map(v2 => v2.map(v3 => v3.map(v4 => {
let ret;
if((ret = m * v4) > cap) ret = cap;
return ret;
}))));
};
You could take a recursive approach by handing over a closure over factor and max value.
const
map = (array, fn) => array.map(v => Array.isArray(v)
? map(v, fn)
: fn(v)
),
fn = (f, max) => v => Math.min(v * f, max);
// call
// newArray = map(array, fn(m, cap))