refactor access seq parsing

This commit is contained in:
harttle
2017-08-03 13:46:00 +08:00
parent 3dc37bf980
commit a2a076d038
2 changed files with 40 additions and 38 deletions
+31 -33
View File
@@ -100,50 +100,48 @@ var Scope = {
propertyAccessSeq: function (str) { propertyAccessSeq: function (str) {
var seq = [] var seq = []
var name = '' var name = ''
for (var i = 0; i < str.length; i++) { var j
if (str[i] === '[') { var i = 0
seq.push(name) while (i < str.length) {
name = '' switch (str[i]) {
case '[':
push()
var delemiter = str[i + 1] var delemiter = str[i + 1]
if (delemiter !== "'" && delemiter !== '"') { if (/['"]/.test(delemiter)) { // foo["bar"]
// foo[bar.coo]
var j = matchRightBracket(str, i + 1)
assert(j !== -1, `unbalanced []: ${str}`)
name = str.slice(i + 1, j)
if (lexical.isInteger(name)) {
// foo[1]
seq.push(name)
} else {
// foo["bar"]
seq.push(this.get(name))
}
name = ''
i = j
} else {
// foo["bar"]
j = str.indexOf(delemiter, i + 2) j = str.indexOf(delemiter, i + 2)
assert(j !== -1, `unbalanced ${delemiter}: ${str}`) assert(j !== -1, `unbalanced ${delemiter}: ${str}`)
name = str.slice(i + 2, j) name = str.slice(i + 2, j)
seq.push(name) push()
name = ''
i = j + 2 i = j + 2
} else { // foo[bar.coo]
j = matchRightBracket(str, i + 1)
assert(j !== -1, `unbalanced []: ${str}`)
name = str.slice(i + 1, j)
if (!lexical.isInteger(name)) { // foo[bar] vs. foo[1]
name = this.get(name)
} }
} else if (str[i] === '.') { push()
// foo.bar i = j + 1
// foo.bar[0].foo }
// In the case of foo.bar[0].foo, must check length because break
// name will be empty after the closing `]` is handled above. case '.':// foo.bar, foo[0].bar
push()
i++
break
default:// foo.bar
name += str[i]
i++
}
}
push()
return seq
function push () {
if (name.length) seq.push(name) if (name.length) seq.push(name)
name = '' name = ''
} else {
// foo.bar
name += str[i]
} }
} }
if (name.length) seq.push(name)
return seq
}
} }
function matchRightBracket (str, begin) { function matchRightBracket (str, begin) {
+4
View File
@@ -42,6 +42,10 @@ describe('scope', function () {
expect(scope.propertyAccessSeq('bar["foo"].zoo')) expect(scope.propertyAccessSeq('bar["foo"].zoo'))
.to.deep.equal(['bar', 'foo', 'zoo']) .to.deep.equal(['bar', 'foo', 'zoo'])
}) })
it('should handle nested access 4', function () {
expect(scope.propertyAccessSeq('foo[0].bar'))
.to.deep.equal(['foo', '0', 'bar'])
})
}) })
describe('#get()', function () { describe('#get()', function () {