Javascript: dotless style in callback

So, I wanted the elements of the array to arr1also belong to the array arr2. I decided that I arr1.filter(arr2.includes)should do the trick, but he gave me an error (see below). Strange, however, arr1.filter(x => arr2.incudes(x))worked fine. Even if the functions arr2.includesand x => arr2.includes(x)are not reference, should not they take the same value on the same inputs? What am I missing here?

> arr1 = ['a', 'b', 'c']
[ 'a', 'b', 'c' ]
> arr2 = ['a', 'c', 'd']
[ 'a', 'c', 'd' ]
>
> arr1.filter(x => arr2.includes(x))
[ 'a', 'c' ]
> arr1.filter(arr2.includes)
TypeError: Cannot convert undefined or null to object
    at includes (<anonymous>)
    at Array.filter (native)
    at repl:1:6
    ... etc ...
+4
source share
2 answers

There are two reasons why you cannot just do arr1.filter(arr2.includes):

  • arr2.includes - , , , , , (arr2). , Function.prototype.bind, :

  • filter , : , . includes , , , filter , .

, -, , includes arr2 , — , .

. Michał Perłakowski answer , .

+5

includes, point-free:

const arr1 = ['a', 'b', 'c'];
const arr2 = ['a', 'c', 'd'];
const includes = arr => x => arr.includes(x);
console.log(arr1.filter(includes(arr2)));
Hide result

JavaScript, Ramda. Ramda :

const arr1 = ['a', 'b', 'c'];
const arr2 = ['a', 'c', 'd'];
// First option: R.flip
console.log(R.filter(R.flip(R.contains)(arr1), arr2));
// Second option: R.__ (placeholder argument)
console.log(R.filter(R.contains(R.__, arr1), arr2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>
Hide result
+3

Source: https://habr.com/ru/post/1679074/


All Articles