I'm looking for a review of the following code.
- Is there a better way to remove all properties that evaluate to truthy for a given function?
- Is there a better way to prevent a stack overflow in the recursive function?
This is the entire Node.js module:
// The removePropertiesWhereTruthy function accepts the following parameters:
//
// 1. an object or array
// 2. a function to call against each non-object or non-array to determine if it's a truthy value according to that function (e.g. _.isNull)
// 3. An optional maxRecursion value to prevent a stack-overflow when there's a circular reference or exceptionally deeply nested objects.
//
'use strict';
var _ = require('lodash');
function removePropertiesWhereTruthy(obj,func,maxRecursion) {
maxRecursion = _.isNumber(maxRecursion) ? maxRecursion - 1 : 20;
if(maxRecursion < 0) {
// prevent stack overflow by allowing caller to set a max time for
// recursion and default to 20 if not set.
return;
}
if(_.isObject(obj) && !_.isArray(obj)) {
_.forOwn(obj, function(v, k) {
if(_.isObject(v)) { // also true for array
return removePropertiesWhereTruthy(v,func,maxRecursion);
} else if(func(v)) {
delete obj[k];
}
});
} else if(_.isArray(obj)) {
_.remove(obj, function(item){
return func(item);
});
_.each(obj, function(v){
if(_.isObject(v)) { // also true for (nested) array
return removePropertiesWhereTruthy(v,func,maxRecursion);
}
});
} else {
throw new Error('This function should only be called with objects and arrays');
}
}
function removePropertiesWithNullValues(obj, maxRecursion) {
return removePropertiesWhereTruthy(obj, _.isNull, maxRecursion);
}
module.exports = {
removePropertiesWithNullValues: removePropertiesWithNullValues
};