Created
April 12, 2015 18:23
-
-
Save lamchau/c93aa3659707a3594ef0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
describe('filterObject', function () { | |
it('should filter out falsey values', function () { | |
var actual = filterObject({ | |
empty: '', | |
depth: 0, | |
nested: { | |
empty: '', | |
depth: 1, | |
nested: { | |
empty: '', | |
str: 'hello', | |
depth: 2, | |
value: false, | |
other: true | |
} | |
} | |
}); | |
var expected = { | |
nested: { | |
depth: 1, | |
nested: { | |
str: 'hello', | |
depth: 2, | |
other: true | |
} | |
} | |
}; | |
expect.expect(actual).to.deep.equal(expected); | |
}); | |
}); |
This file contains hidden or 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
function filterObject(object, predicate) { | |
if (typeof predicate !== 'function') { | |
predicate = function(value, key, o) { | |
if (!value) { | |
delete o[key]; | |
} | |
}; | |
} | |
if (typeof object === 'object') { | |
for (var key in object) { | |
predicate.call(this, object[key], key, object); | |
filterObject(object[key], predicate); | |
} | |
} | |
return object; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment