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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.