Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement