Created
May 18, 2023 09:27
-
-
Save Misaka-0x447f/34cb51bb1558fb86f089a4cde5b2fde0 to your computer and use it in GitHub Desktop.
面试记录>Extended get method
This file contains 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
const getx = (input, expression) => { | |
if (!expression.length) return input | |
expression = expression.split('.') | |
const arrayMatch = expression[0].match(/(?<propName>\w+)\[(?<number>\d+)]/) | |
const functionMatch = expression[0].match(/(?<propName>\w+)\((?<arguments>.*)\)/) | |
if (arrayMatch) { | |
return getx(input[arrayMatch.groups.propName][arrayMatch.groups.number], expression.slice(1).join('.')) | |
} | |
if (functionMatch) { | |
const argString = functionMatch.groups.arguments.split(',') | |
return getx(input[functionMatch.groups.propName](...functionMatch.groups.arguments.length ? argString.map(JSON.parse) : []), expression.slice(1).join('.')) | |
} | |
return getx(input[expression[0]], expression.slice(1).join('.')) | |
} | |
console.log(getx({a:{b:{c:100}}}, 'a.b.c')) /* 100 */ | |
console.log(getx({a:{b:{c:100}}}, 'a.b.c.d')) /* undefined */ | |
console.log(getx({a:{b:[{c:100}]}}, 'a.b[0].c')) /* 100 */ | |
console.log(getx({a:{b:{c:function(){return {d:100}}}}} , 'a.b.c().d')) /* 100 */ | |
console.log(getx({a:{b:{c:function(factor){return {d:100 * factor}}}}} , 'a.b.c(10).d')) /* 1000 */ | |
console.log(getx({a:{b:{c:function(x, y){return {d: x * y}}}}} , 'a.b.c(10, 20, "a").d')) /* 200 */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment