Skip to content

Instantly share code, notes, and snippets.

@justsml
Forked from dhigginbotham/transformy.js
Last active September 14, 2016 00:26
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 justsml/036e016bfdac81b9218a9a7a506a7770 to your computer and use it in GitHub Desktop.
Save justsml/036e016bfdac81b9218a9a7a506a7770 to your computer and use it in GitHub Desktop.
// transformy is an object mapping tool to
// transform objects to another object defaults
function transformy({ mutate = {}, input = {}, schema = {}, omit = [], loose = true }) {
return Object.keys(input).map((key) => {
const mutated = {};
const tkey = mutate.hasOwnProperty(key) ? mutate[key] : null;
if (omit.indexOf(key) !== -1) return mutated;
if (typeof input[key] !== 'undefined' && schema.hasOwnProperty(tkey)) {
mutated[tkey] = input[key];
} else if (typeof schema[key] !== 'undefined') {
mutated[key] = schema[key];
} else if (loose === true && typeof input[key] !== 'undefined') {
mutated[key] = input[key];
}
return mutated;
})
.filter(obj => Object.keys(obj).length)
.reduce((a, b) => {
Object.keys(b).forEach(key => a[key] = b[key]);
return a;
}, {});
};
// transformy({
// mutate: {
// token: 'token',
// webApp: 'web',
// isMaster: 'master',
// registeredActions: 'actions',
// fullSchemas: 'schemas',
// owner: 'ownerId',
// nodeEnv: 'env'
// },
// input: {
// token: 1234,
// webApp: true,
// isMaster: true,
// web: true,
// registeredActions: ['herro'],
// schemas: { example: [] },
// ownerId: 1337,
// env: 'production',
// looseKey: 'gotheem',
// omitKey: 'lessee'
// },
// schema: {
// token: 0,
// web: false,
// master: false,
// actions: [],
// schemas: {},
// room: 1,
// ownerId: 1,
// env: 'development'
// },
// omit: ['omitKey'],
// loose: true
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment