Created
April 15, 2015 22:10
-
-
Save narqo/43145fa571e3737d8fa7 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
function Path(path) { | |
this.path = this.parsePathStr(path); | |
console.log(this.path); | |
this.length = this.path.length; | |
/** @override */ | |
this.get = this.createGetFn(); | |
} | |
Path.prototype.get = function(obj) { | |
for(var i = 0; i < this.length; i++) | |
if((obj = obj[this.path[i]]) == null) return; | |
return obj; | |
}; | |
Path.prototype.parsePathStr = function(str) { | |
return str.split('.'); | |
}; | |
Path.prototype.createGetFn = function() { | |
var key = 'obj', | |
fnBody = 'if(' + key; | |
for(var i = 0; i < this.length - 1; i++) { | |
key += '.' + this.path[i]; | |
fnBody += ' &&\n' + key + '!=null'; | |
} | |
key += '.' + this.path[i]; | |
fnBody += ') return ' + key + ';'; | |
return new Function('obj', fnBody); | |
}; | |
function test() { | |
var obj = { | |
a : { | |
b : { | |
c : [ | |
1, | |
{ d : [1, 2, 3] }, | |
{ d : [4, 5] } | |
] | |
} | |
} | |
}; | |
var path = new Path('a.b.c[1].d'); | |
var res = path.get(obj); | |
console.log(res); | |
} | |
test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment