2

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;
    }))));
};
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Rewind
  • 2,554
  • 3
  • 30
  • 56
  • Please show your input structure and expected output. You could use recursion to drill down to the values using `Array.isArray(arr)` -- if it is, recurse on its elements, if not, perform the operation on the scalar. `if((ret = m * v4) > cap) ret = cap;` should be written as `return Math.min(cap, m * v4)` – ggorlen Aug 20 '21 at 17:45
  • What does "better" mean, objectively? Apparently someone guessed at what "better" meant and got the checkmark, but for future answerers and people looking for something other than your opinion about what is better, please explain. – Heretic Monkey Aug 20 '21 at 18:28
  • As explained in the question, better = not messy. As explained in the question, better = future-proof independent of the dimension of the array. Better in general, is better written code. My code was messy. Nina's answer is slick, well written code, using good fundamental ideas in functional programming. Nina's code is something I aspire to. – Rewind Aug 20 '21 at 18:33
  • ...and @ggorlen 's comment is saying exactly the same answer. Thanks ggorlen as well. – Rewind Aug 20 '21 at 18:39

1 Answers1

1

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))
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392