Skip to content

Instantly share code, notes, and snippets.

@pschichtel
Created February 13, 2016 15:10
Show Gist options
  • Save pschichtel/def73711a3dfa67487f2 to your computer and use it in GitHub Desktop.
Save pschichtel/def73711a3dfa67487f2 to your computer and use it in GitHub Desktop.
function compile(selector) {
function identity(x) {
return x
}
function compose(f, access) {
return function(x) {
let r = f(x)
if (r && access in r) return r[access]
else return null
}
}
let f = identity
let readingFieldAccess = false
let readingArrayAccess = false
let fieldName = ''
let arrayIndex = ''
let escaped = false
for (let c of (selector + '.')) {
if (readingFieldAccess && readingArrayAccess) {
throw new Error('Illegal state!');
} else if (readingFieldAccess) {
if (c == '\\' && !escaped) {
escaped = true
} else if ((c == '[' || c == '.') && !escaped) {
if (fieldName == '') throw new Error('Empty field name')
f = compose(f, fieldName)
fieldName = ''
readingFieldAccess = c != '['
readingArrayAccess = c == '['
} else {
escaped = false
fieldName += c
}
} else if (readingArrayAccess) {
if (c == ']') {
if (arrayIndex == '') throw new Error('Empty array index')
f = compose(f, parseInt(arrayIndex))
arrayIndex = ''
readingFieldAccess = false
readingArrayAccess = false
} else if (/\d/.test(c)) {
arrayIndex += c
} else {
throw new Error('Illegal array index!')
}
} else if (!readingFieldAccess && !readingArrayAccess) {
if (c == '.') readingFieldAccess = true
else if (c == '[') readingArrayAccess = true
else throw new Error('Invalid expression!')
}
}
return f
}
let obj = {
passengers: [
{
flights: [
{
segments: [
{
services: {
seat: {
number: '1A'
}
}
},
{
services: {
seat: {
number: '2A'
}
}
}
]
}
]
}
]
}
function t(selector, obj) {
let compiled = compile(selector)
console.log(selector, obj, compiled, compiled(obj))
}
t('.passengers[0].flights[0].segments[1].services.seat.number', obj)
t('.passengerss.bla', obj)
t('.', obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment