Skip to content

Instantly share code, notes, and snippets.

@nicklozon
Last active April 13, 2017 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicklozon/0ac061b236b655f38d02f5f5bc555bee to your computer and use it in GitHub Desktop.
Save nicklozon/0ac061b236b655f38d02f5f5bc555bee to your computer and use it in GitHub Desktop.
var _ = require('lodash');
/**
* Takes two objects and a callback. One schema object that contains nested
* objects and functions, the other a paramater object with no constraints. The
* schema object is traversed recursively and functions are evaluated in place
* using the parameter object as the only parameter. The final evaluated object
* is passed to the callback.
* @param {Object} obj
* @param {Object} params
* @param {requestCallback} cb
*/
function mapSchema(obj, params, cb) {
var mapValues;
// Recursive functon to evaluate function objects
// Omits any values of undefined or null
mapValues = function(obj, params) {
return _
.chain(obj)
.mapValues(function(val) {
if(typeof(val) === 'function') {
return val(params);
} else if(typeof(val) === 'object') {
return mapValues(val, params);
} else {
return val;
}
})
.omitBy(_.isUndefined)
.omitBy(_.isNull)
.value();
};
try {
cb(mapValues(obj, params));
} catch (ex) {
cb(ex);
}
}
module.exports = mapSchema;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment