Created
July 14, 2020 21:53
-
-
Save pschichtel/81019834d5891711906f357eebb51616 to your computer and use it in GitHub Desktop.
A simple typescript script that parses json paths and composes a lense function
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 extractorFor(selector: String): (x: any) => any { | |
function composeAccess(f: (x: any) => any, field: string): (x: any) => any { | |
return (x: any) => { | |
let r = f(x) | |
if (field in r) return r[field] | |
else return null | |
} | |
} | |
function identity(x: any): any { | |
return x | |
} | |
function nonEmpty(x: string): boolean { | |
return x != "" | |
} | |
function unescape(x: string): string { | |
return x.replace('~1', '/').replace('~0', '~') | |
} | |
return selector.split('/') | |
.filter(nonEmpty) | |
.map(unescape) | |
.reduce(composeAccess, identity) | |
} | |
function extract(o: any, selector: string): any { | |
return extractorFor(selector)(o) | |
} | |
let selector = "/passengers/0/flights/0/segments/0/services/seat/number~1a" | |
let compiled = extractorFor(selector) | |
let obj = { | |
passengers: [{ | |
flights: [{ | |
segments: [{ | |
services: { | |
seat: { | |
"number/a": '1A' | |
} | |
} | |
}] | |
}] | |
}] | |
} | |
console.log("object", JSON.stringify(obj)) | |
console.log("selector", selector) | |
console.log("result", compiled(obj)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment