Created
April 3, 2015 15:29
-
-
Save fonji/6c1895ed9b1cc2666128 to your computer and use it in GitHub Desktop.
_.deepWhere
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# _.deepWhere | |
# same as _.where but supports comparison of arrays as attributes | |
# https://gist.github.com/fonji/6c1895ed9b1cc2666128 | |
# | |
# Example: | |
# _.deepWhere({foo: 'foo', bar: [{a: 'b'}]}, {bar: [{a: 'b'}]}) | |
# Changelog: | |
# v0.1.0 creation (fonji) | |
# Returns whether an object has a given set of key:value pairs. | |
_.mixin( | |
deepIsMatch: (object, attrs) -> | |
keys = _.keys attrs | |
length = keys.length | |
return !length if object == null | |
obj = Object object | |
objKeys = _.keys obj | |
for key in keys | |
return false unless key in objKeys | |
if (_.isArray(attrs[key]) && _.isArray(obj[key])) || | |
(_.isObject(attrs[key]) && _.isObject(obj[key])) | |
return false unless _.deepIsMatch(attrs[key], obj[key]) | |
else | |
return false if attrs[key] != obj[key] | |
true | |
deepMatches: (attrs) -> | |
attrs = _.extendOwn({}, attrs) | |
return (obj) -> | |
return _.deepIsMatch(obj, attrs) | |
deepWhere: (obj, attrs) -> | |
_.filter obj, _.deepMatches(attrs) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment