Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const reduceToObj = (a,b) => {
- a[b[0]] = b[1]
- return a
- }
- const queryOnlyObj = (obj,query) => {
- return typeof obj === "object"?JOQL(obj, query):obj
- }
- const splitAtLast = (string,delim) => {
- const idx = string.lastIndexOf(delim)
- if (idx > 0){
- return [string.substring(0,idx),string.substring(idx+1)]
- } else {
- return [string]
- }
- }
- const JOQL = (obj, query) => {
- if(query === "" || !query) {
- return obj
- } else {
- let queryArray = query.split("/")
- let key = queryArray.splice(0,1)[0]
- let rest = queryArray.join("/")
- let type = key[0]
- let regex = key.substring(1)
- let lift, label ,output
- if (type === "}" || type === "{"){
- const entries = Object.entries(obj)
- const split = splitAtLast(regex,":")
- label = split[1]
- lift = label === "^"
- if (lift) label = false
- regex = split[0]
- regex = new RegExp(regex)
- output = entries.filter(([key]) => key.match(regex))
- .map(e => {
- if (label){
- return [e[1][label],queryOnlyObj(e[1],rest)]
- } else {
- return [e[0],queryOnlyObj(e[1],rest)]
- }
- })
- .filter(x=>x[1]!==undefined)
- }
- switch (type) {
- case "{" :
- //expand regex, need to use var here because there's only one scope per switch
- return output.reduce(reduceToObj, lift?[]:{})
- break
- case "}" :
- //collect regex
- //[[key,value],...]
- if (lift){
- return output.reduce((carry,obj) => {
- let entries = Object.entries(obj[1])
- entries.forEach(e => {
- if (!carry[e[0]]){
- carry[e[0]] = []
- }
- carry[e[0]].push(e[1])
- })
- return carry
- }, {})
- } else {
- return output.reduce((carry,obj) => {
- let entries = Object.entries(obj[1])
- entries.forEach(e => {
- if (!carry[e[0]]){
- carry[e[0]] = []
- }
- carry[e[0]].push({[obj[0]]:e[1]})
- })
- return carry
- }, {})
- }
- break
- default:
- return queryOnlyObj(obj[key],rest)
- break
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement