diff --git a/package.json b/package.json index be78a13..6ac1544 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,9 @@ "license": "WTFPL", "dependencies": { "checkit": "^0.7.0", - "default-value": "^1.0.0" + "deep-assign": "^2.0.0", + "default-value": "^1.0.0", + "dotty": "0.0.2" }, "devDependencies": { "@joepie91/gulp-preset-es2015": "^1.0.1", diff --git a/src/property-mapper.js b/src/property-mapper.js new file mode 100644 index 0000000..5975442 --- /dev/null +++ b/src/property-mapper.js @@ -0,0 +1,82 @@ +'use strict'; + +const dotty = require("dotty"); +const deepAssign = require("deep-assign"); + +module.exports = function createPropertyMapper(propertyMap) { + let mappings = Object.keys(propertyMap).map((sourceProperty) => { + let destinationPath = propertyMap[sourceProperty]; + + if (typeof destinationPath === "function") { + return { + sourceProperty: sourceProperty, + transformer: destinationPath + } + } else { + let destinationPathParts = destinationPath.split("."); + let destinationObject = destinationPathParts[0]; + let destinationProperty = destinationPathParts.slice(1).join("."); + + return { + sourceProperty: sourceProperty, + destinationObject: destinationObject, + destinationProperty: destinationProperty + } + } + }); + + return function mapProperties(properties) { + return mappings.map((mapping) => { + if (properties[mapping.sourceProperty] != null) { + return Object.assign({ + value: properties[mapping.sourceProperty] + }, mapping); + } + }).filter((item) => { + return (item != null); + }).reduce((objects, item) => { + function ensureObject(object) { + if (objects[object] == null) { + objects[object] = {}; + } + } + + if (item.destinationProperty != null) { + ensureObject(item.destinationObject); + dotty.put(objects[item.destinationObject], item.destinationProperty, item.value); + } else { + let results = item.transformer(item.value); + + Object.keys(results).forEach((object) => { + ensureObject(object); + deepAssign(objects[object], results[object]); + }); + } + + return objects; + }, {}) + } +}; + +let mapper = module.exports({ + foo: "one.foo", + bar: "two.bar", + twoFoo: "two.foo", + baz: (value) => { + return { + one: { + baz: value + }, + two: { + baz: value + } + } + } +}); + +console.log(mapper({ + foo: "hello one foo!", + bar: "hello bar!", + twoFoo: "hello two foo!", + baz: "hello baz!" +}));