1

Given existing googleable knowledge of function.bind and such, and the following control code:

console.log( [1, 2, 3].includes(2) ) // --> `true` 
console.log( [null].map(String.prototype.toUpperCase, "abc") ) // --> `["ABC"]`  
console.log( Array.prototype.includes.bind([3, 4, 5])(1) ) //--> `false`  
console.log( Array.prototype.includes.bind([3, 4, 5])(4) ) // -- > `true`

_ is underscorejs, a generic utility wrapper/polyfill thing

[1, 2, 3].some(_.prototype.includes.bind(_([3, 4, 5]))) // --> `true`

But, why does this code yield this unexpected result?

console.log(
  [1,2,3].some(Array.prototype.includes.bind([3,4,5])) // --> `false`
)

Edit: I know this code is bad form in its literal form, but this is a POC, the real implementation will differ (and cannot use arrow functions, thanks IE)

1

2 Answers 2

3

This is the syntax for includes:

arr.includes(valueToFind, [fromIndex])

There is an optional second parameter fromIndex.

fromIndex: The position in this array at which to begin searching for valueToFind

So, your code becomes something like this:

[1,2,3].some((a,index) => Array.prototype.includes.bind([3,4,5])(a, index))
// OR
[1,2,3].some((a, index) => [3,4,5].includes(a, index))

It is looking for 3 starting from the index = 2.

So, if you were to change it like this, it will return true

console.log(
  // looks for from index=0
  [3,2,1].some(Array.prototype.includes.bind([5,4,3]))
)

Sign up to request clarification or add additional context in comments.

1 Comment

ah dangit, you and @Grillparzer are right, the some index variable is passed into the includes fromIndex, breaking the concept. It works with underscore because it doesn't use a second variable. Thanks for pointing it out, I was overlooking this
2

What you may not be expecting is that .some() invokes the bound function with three parameters, and not just the one that contains the value.

You can check this with [1,2,3].some(console.log)

Array.includes accepts two parameters, one for the value and an optional one that offsets the start location.

A solution would be:

[3,2,1].some(n => Array.prototype.includes.bind([5,4,3])(n))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.