Array::where = (query) ->
return [] iftypeof query isnt "object"
hit = Object.keys(query).length
@filter (item) ->
match = 0for key, val of query
match += 1if item[key] is val
if match is hit then trueelsefalse
cats.where age:1
# => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 },{ name: 'flyingCat', favoriteFood: 'mice', age: 1 } ]
cats.where age:1, name: "Bubbles"
# => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 } ]
cats.where age:1, favoriteFood:"tuna"
# => []
討論
這是一個(gè)確定的匹配。我們能夠讓匹配函數(shù)更加靈活:
Array::where = (query, matcher = (a,b) -> a is b) ->
return [] iftypeof query isnt "object"
hit = Object.keys(query).length
@filter (item) ->
match = 0for key, val of query
match += 1if matcher(item[key], val)
if match is hit then trueelsefalse
cats.where name:"bubbles"
# => []
# it's case sensitive
cats.where name:"bubbles", (a, b) -> "#{ a }".toLowerCase() is "#{ b }".toLowerCase()
# => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 } ]
# now it's case insensitive
更多建議: