diff --git a/index.js b/index.js deleted file mode 100644 index 437a026..0000000 --- a/index.js +++ /dev/null @@ -1,39 +0,0 @@ -function getValueFromPath(obj, path) { - return function() { - try { - return path.reduce((node, v) => node[v], obj) - } - catch(e) { - return - } - } -} - -export default function getify(obj) { - const path = [] - function handler(path) { - return { - get: function(target, key){ - if (typeof key == 'symbol' || key == '__proto__') { - return target[key] - } - - // Add key onto path - const newPath = [...path, key] - - return getProxy(getValueFromPath(obj, newPath), newPath) - } - } - } - - function getProxy(obj, path) { - return new Proxy(obj, handler(path)) - } - - // For consistency's sake, we return the root object as a function - function getRoot() { - return obj; - } - - return getProxy(getRoot , path) -} diff --git a/package.json b/package.json new file mode 100644 index 0000000..fc24588 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "getify", + "version": "0.0.1", + "description": "", + "main": "lib/getify.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/johnste/getify.git" + }, + "author": "John Sterling ", + "license": "MIT", + "bugs": { + "url": "https://github.com/johnste/getify/issues" + }, + "homepage": "https://github.com/johnste/getify#readme" +} diff --git a/src/getify.js b/src/getify.js new file mode 100644 index 0000000..6a40736 --- /dev/null +++ b/src/getify.js @@ -0,0 +1,55 @@ +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([], factory); + } else if (typeof module === 'object' && module.exports) { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + module.exports = factory(); + } else { + // Browser globals (root is window) + root.getify = factory(); + } +}(this, function () { + + function getify(obj) { + const path = [] + + function getValueFromPath(obj) { + return (val) => { + try { + return path.reduce((node, v) => node[v], obj) || val + } + catch(e) { + return val + } + } + } + + function handler() { + return { + get: function(target, key){ + if (typeof key == 'symbol' || key == '__proto__') { + return target[key] + } + + path.push(key) + return getProxy(getValueFromPath(obj)) + } + } + } + + function getProxy(obj, path) { + return new Proxy(obj, handler()) + } + + // For consistency's sake, we return the root object as a function + return getProxy(() => obj, path) + } + + // Just return a value to define the module export. + // This example returns an object, but the module + // can return a function as the exported value. + return getify; +})); \ No newline at end of file