1

I am referring to where it returns the function findMatches to substringMatcher. Does substringMatcher take one or two params now?

var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
    var matches, substringRegex;

    // an array that will be populated with substring matches
    matches = ["Your Location"];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
        };
};
user700077
  • 93
  • 2
  • 9
  • 5
    That's a higher-order function. It takes one argument, and returns a function that takes two arguments. You'd write `substringMatcher(a)(b, c)` – elclanrs Jun 05 '15 at 09:15

1 Answers1

3

This is a closure. For explanation I strongly recommend to go through this. Couldn't explain it better myself. I will just quote from there:

Simply accessing variables outside of your immediate lexical scope creates a closure.

For calling your function, you can write substringMatcher(strs)(q, cb); so the answer is that substringMatcher takes one parameter and returns a function, that takes two. You could also write:

var findMatches = substringMatcher(strs);
var result = findMatches(q, cb);
Community
  • 1
  • 1
mcs_dodo
  • 738
  • 1
  • 10
  • 17