0

I need to create a function which I will pass to my database server. The returned function will take a single item as a parameter and compare that item to a list of requirements.

For this I need a function generating function that takes an array as it's argument and returns the inner function which has that array built in to it.

Here's an example:

function create_query (list_of_requirements) {
  return function (item) {
    var is_match = true
    // the next function sets is_match to false if the item fails
    list_of_requirements.forEach(check_if_item_meets_requirement)
    return is_match
  }
}

An example of using this:

function search (parsed_user_string) {
  db.get(create_query(parsed_user_string)).then(function(results){
    show_results(results)
  })
}

How can I build the list of requirements into the inner function?

  • 1
    It looks like you're already doing that. What's the problem you're having? – Barmar May 08 '15 at 23:41
  • I see two issues: you're never calling the function that `create_query()` returns. Second, I assume `db.get()` expects its argument to be a query string, but your function just returns a boolean. – Barmar May 08 '15 at 23:43
  • `check_if_item_meets_requirements` also needs to be in the scope of the inner function so it can assign to `is_match`. – Barmar May 08 '15 at 23:44
  • If the argument to `db.get` is supposed to be a callback, then it looks like you're calling it correctly. – Barmar May 08 '15 at 23:45
  • db.get needed to take a function as it's argument, and returns a promise. my answer below addresses the issues using a closure. – Ryan Harrigan May 08 '15 at 23:56

1 Answers1

0

I needed to use a closure.

Here's a simpler example of a solution.

function makePrinter (num) {
  (return function () {
    print(num)
    })
}

and then:

var print5 = makePrinter(5)
print5() > prints 5!

I still don't quite get how closures accomplish this, but there it is.