codecombat/app/lib/LocalMongo.coffee

37 lines
1.9 KiB
CoffeeScript
Raw Normal View History

2014-05-13 15:09:54 -04:00
LocalMongo = module.exports
# Checks whether func(l, r) is true for at least one value of left for at least one value of right
mapred = (left, right, func) ->
_.reduce(left, ((result, singleLeft) ->
result or (_.reduce (_.map right, (singleRight) -> func(singleLeft, singleRight)),
((intermediate, value) -> intermediate or value), false)), false)
2014-05-13 18:08:22 -04:00
doQuerySelector = (value, operatorObj) ->
value = [value] unless _.isArray value # left hand can be an array too
2014-05-13 15:09:54 -04:00
for operator, body of operatorObj
body = [body] unless _.isArray body # right hand can be an array too
2014-05-13 15:09:54 -04:00
switch operator
when '$gt' then return false unless mapred value, body, (l, r) -> l > r
when '$gte' then return false unless mapred value, body, (l, r) -> l >= r
when '$lt' then return false unless mapred value, body, (l, r) -> l < r
when '$lte' then return false unless mapred value, body, (l, r) -> l <= r
when '$ne' then return false if mapred value, body, (l, r) -> l == r
2014-05-13 18:08:22 -04:00
when '$in' then return false unless _.reduce value, ((result, val) -> result or val in body), false
when '$nin' then return false if _.reduce value, ((result, val) -> result or val in body), false
2014-05-13 15:09:54 -04:00
true
LocalMongo.doLogicalOperator = (target, operatorObj) ->
for operator, body of operatorObj
switch operator
2014-05-13 18:08:22 -04:00
when '$or' then return false unless _.reduce body (res, query) -> res or matchesQuery target query, false
when '$and' then return false unless _.reduce body (res, query) -> res and matchesQuery target query, true
2014-05-13 15:09:54 -04:00
2014-05-13 18:08:22 -04:00
LocalMongo.matchesQuery = (target, queryObj) =>
for prop, query of queryObj
return false unless prop of target
if typeof query != 'object' or _.isArray query
return false unless target[prop] == query or (query in target[prop] if _.isArray target[prop])
else return false unless doQuerySelector(target[prop], query)
true