Skip to content

Instantly share code, notes, and snippets.

@dhigginbotham
Last active September 14, 2016 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dhigginbotham/53c40bde9bdd0af6e31549efe698debd to your computer and use it in GitHub Desktop.
Save dhigginbotham/53c40bde9bdd0af6e31549efe698debd to your computer and use it in GitHub Desktop.
// transformy is an object mapping tool to
// transform objects to another object defaults
function extenze() {
const args = Array.prototype.slice.call(arguments);
const source = args.shift();
let current;
while (current = args.shift()) {
Object.keys(current).forEach((key) => {
source[key] = typeof current[key] === 'object'
? extenze({}, current[key])
: current[key];
});
}
return source;
}
function transformy(opts) {
const { mutate = {}, input = {}, schema = {}, omit = [], loose = true } = opts;
const output = Object.keys(input).map((key) => {
const mutated = {};
if (omit.indexOf(key) !== -1) return mutated;
const tkey = mutate.hasOwnProperty(key) ? mutate[key] : null;
if (typeof input[key] !== 'undefined'
&& schema.hasOwnProperty(tkey)) {
mutated[tkey] = typeof input[key] === 'object' ? extenze({}, input[key]) : input[key];
return mutated;
}
if (schema.hasOwnProperty(key)) mutated[key] = typeof schema[key] === 'object' ? extenze({}, schema[key]) : schema[key];
if (loose === true && typeof input[key] !== 'undefined') {
mutated[key] = typeof input[key] === 'object' ? extenze({}, input[key]) : input[key];
}
return mutated;
})
.filter(obj => Object.keys(obj).length)
.reduce((a, b) => {
if (typeof a === 'undefined') a = {};
Object.keys(b).forEach(key => a[key] = b[key]);
return a;
});
return output;
};
module.exports = transformy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment