0

I am looking at the documentation here but can not find what I am looking for.

What I would like to achieve is something like this:

 var valueToSearchFor = "something"

 function SearchArray(currentIndex, valueToSearchFor){
    return currentIndex.PropertyName === valueToSearchFor;
 }

 var attribute = myArray.find(SearchArray(valueToSearchFor));

rather than:

 var valueToSearchFor = "something"

 function SearchArray(currentIndex){
    return currentIndex.PropertyName === valueToSearchFor;
 }

 var attribute = myArray.find(SearchArray);

In my case the valueToSearchFor is not thread safe. Am I missing something?

user1234
  • 83
  • 1
  • 5
  • 4
    *"In my case the valueToSearchFor is not thread safe"* Uh, what? How is that possible? – Alexander O'Mara Jan 31 '17 at 02:44
  • 1
    Could you maybe include a more specific reason as to what you mean by "_`valueToSearchFor` is not thread safe_"? JavaScript is single threaded – Nick Zuber Jan 31 '17 at 02:46
  • A similar question was just asked: http://stackoverflow.com/questions/41947031/passing-additional-parameters-in-higher-order-functions . Maybe you can find your answer there. – mrlew Jan 31 '17 at 02:48
  • If you change `SearchArray` to `function SearchArray(valueToSearchFor){ return function(currentIndex) { return currentIndex.PropertyName === valueToSearchFor; }; }` then your first example would work. But I still question whether you actually need to do that. – Felix Kling Jan 31 '17 at 02:49

1 Answers1

1

I'm not sure what you mean by:

in my case the valueToSearchFor is not thread safe

But regardless, you can still achieve this kind of functionality with currying:

var valueToSearchFor = "something";

function createSearchArray (valueToSearchFor) {
  return function (currentIndex) {
    return currentIndex.PropertyName === valueToSearchFor;
  }
}

var attribute = myArray.find(createSearchArray(valueToSearchFor));

The idea here is to create the function you're looking for using your valueToSearchFor variable. We then return this function to .find().

Nick Zuber
  • 5,467
  • 3
  • 24
  • 48
  • In my case I am using web sockets which are not guaranteed to return values in order and all open connections have the same callback – user1234 Jan 31 '17 at 03:02
  • @user1234 Ah okay. The sample code I provided is akin to a function builder, such that you give `createSearchArray` an argument for some `valueToSearchFor` and it will return a "search array" type function you can use with `.find()` — does that help with your issue? – Nick Zuber Jan 31 '17 at 03:04
  • 1
    Three cheers for [partial applications](http://benalman.com/news/2012/09/partial-application-in-javascript/)! – Sukima Jan 31 '17 at 03:21
  • @Sukima Functional programming always comes to the rescue ;) – Nick Zuber Jan 31 '17 at 03:23