0

What is the principle behind this? newArr.some(Array.isArray) === newArr.some(elem => Array.isArray(elem))

How is posible that they are parsed as equal? I thought that newArr.some(Array.isArray) === newArr.some(Array.isArray()) (assuming that some is a loop and that JS assumed each val as the implicit arg of the func), but it's not. So, I'm confused. Please, help me.

Here, there are 2 applications of the cases above:


function flatMultiArr(arr) {
let newArr = [].concat(...arr);
return newArr.some(Array.isArray)
? flatMultiArr(newArr)
: newArr
}

console.log();//[ 1, {}, 3, 4 ]

function flatMultiArr(arr) {
let newArr = [].concat(...arr);
return newArr.some(elem => Array.isArray(elem))
? flatMultiArr(newArr)
: newArr
}

console.log();//[ 1, {}, 3, 4 ]

Note this question is not about how to flatten multidimentional arrays.

paulocleon
  • 109
  • 9
  • 3
    `.some` takes a callback function. You can pass a function directly in, or wrap it in an anonymous function. It's the same thing more or less. `arr.some(e => (e => Array.isArray(e))(e))` works too--you can just keep adding layers of indirection for no reason. – ggorlen Apr 20 '20 at 18:12
  • 1
    "I thought that `newArr.some(Array.isArray) === newArr.some(Array.isArray())`" No, absolutely not. `newArr.some(Array.isArray())` isn't passing a callback at all, rather, the result of calling the function which is supposed to be used as a callback, which probably doesn't work. A callback is a *function*, so you need to pass the function, i.e. `Array.isArray`, not the *result of calling the function*, `Array.isArray()` – juanpa.arrivillaga Apr 20 '20 at 23:27

2 Answers2

4

This principle is known as eta conversion. No, they are not "parsed as equal", they are different functions, but they behave the same, and therefore can be reasoned about equally. To simplify:

const f = Array.isArray

and

function f(x) { return Array.isArray(x); }

will have the same results when called1, i.e. f([]) or f(5).

1: In general, there are minor differences wrt to the this binding in the method and the number of arguments, but it works for Array.isArray.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks Bergi. I was useful the reference to calculus. I' getting material in that area to improve my functional programming – paulocleon Apr 21 '20 at 15:20
2

Please note that callbacks are just functions. It is called eta-abstraction and makes your function slightly more lazy:

const fix  = f =>      f(fix( f));
const fix_ = f => x => f(fix_(f)) (x);
//                ^^^^            ^^^ eta abstraction

try {
const map = fix(go => f => ([x, ...xs]) =>
    x == undefined
      ? []
      : go(f) (xs).concat(f(x)));
}

catch (e) {
  console.log(e.message);
}

const map_ = fix_(go => f => ([x, ...xs]) =>
    x === undefined
      ? []
      : [f(x)].concat(go(f) (xs)));

console.log(
  map_(x => x * x) ([1,2,3]));