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 个解决方案
#1
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.
我仍然不太明白闭包是如何实现这一目标的,但事实确实如此。
#1
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.
我仍然不太明白闭包是如何实现这一目标的,但事实确实如此。