Last active
June 23, 2016 11:10
-
-
Save sergueyarellano/5061081b29d74caf0e6e9eafe9400cb3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var puntillo = (function () { | |
function get(parent, nested, defValue) { | |
return splitMy(nested) | |
.reduce(function(acc, current) { | |
return acc ? acc[current] : defValue; | |
}, parent); | |
} | |
function set(parent, nested, defValue) { | |
return splitMy(nested) | |
.reduce(function(acc, current, index, arr) { | |
acc[current] = typeof acc[current] !== 'undefined' ? | |
acc[current] : | |
(index === arr.length -1 ? defValue : {}); | |
return acc[current]; | |
}, parent) | |
} | |
function splitMy (nested) { | |
return nested.split(/[\.\["'\]]/).filter(Boolean); | |
} | |
var methods = { | |
get: get, | |
set: set | |
}; | |
return (function (fn, parent, nested, defValue) { | |
return methods[fn].apply(null, [].slice.call(arguments, 1)) | |
}); | |
})(); | |
var ns = {a:{b:{c:0}}}; | |
console.log(puntillo('get', ns, 'a.b.d.e')) // undefined | |
console.log(puntillo('get', ns, 'a.b.d.e', 3)) // 3 | |
console.log(puntillo('set', ns, 'a.b.d.e.h', 7)); // 7 -> creates namespace a.b.d.e.h === 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment