1

I'm trying to understand how the following code works :

Btw this is a solution of this problem:

function getPINs(observed) {
  return observed.split('')
  .map( t => ({
    '0': [ '0', '8' ],
    '1': [ '1', '2', '4' ],
    '2': [ '1', '2', '3', '5' ],
    '3': [ '2', '3', '6' ],
    '4': [ '1', '4', '5', '7' ],
    '5': [ '2', '4', '5', '6', '8' ],
    '6': [ '3', '5', '6', '9' ],
    '7': [ '4', '7', '8' ],
    '8': [ '5', '7', '8', '9', '0' ],
    '9': [ '6', '8', '9' ]
  }[t]))
  .reduce((pre, cur)=> [].concat.apply([], pre.map(t => cur.map(g => t + g))));
}

when I delete concat method from the code the result is unexpectedly different, as an example, I thought that the result without concat when calling getPINs(456) is [['123'],['125'], ...] instead of [123, 125, ...]

  • Just try logging `pre` and `cur` at each step and you should be able to figure it out – Bergi Jul 13 '22 at 19:17
  • Btw, the modern way of writing this would be `(pre, cur)=> pre.flatMap(t => cur.map(g => t + g))`. Also `reduce` is missing the initial value, which should be `['']`. – Bergi Jul 13 '22 at 19:19
  • It's basically building the cartesian product of all the variation arrays - [so many ways to do that](https://stackoverflow.com/questions/15298912/javascript-generating-combinations-from-n-arrays-with-m-elements/15310051#comment28286502_15298912)… – Bergi Jul 13 '22 at 19:21

0 Answers0