Advertisement
Guest User

it's only a prank bro

a guest
May 23rd, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const reduceToObj = (a,b) => {
  2.   a[b[0]] = b[1]
  3.   return a
  4. }
  5.  
  6. const queryOnlyObj = (obj,query) => {
  7.   return typeof obj === "object"?JOQL(obj, query):obj
  8. }
  9.  
  10. const splitAtLast = (string,delim) => {
  11.   const idx = string.lastIndexOf(delim)
  12.   if (idx > 0){
  13.     return [string.substring(0,idx),string.substring(idx+1)]
  14.   } else {
  15.     return [string]
  16.   }
  17. }
  18.  
  19. const JOQL = (obj, query) => {
  20.   if(query === "" || !query) {
  21.     return obj
  22.   } else {  
  23.     let queryArray = query.split("/")
  24.     let key = queryArray.splice(0,1)[0]
  25.     let rest = queryArray.join("/")
  26.     let type = key[0]
  27.     let regex = key.substring(1)
  28.  
  29.     let lift, label ,output
  30.     if (type === "}" || type === "{"){
  31.       const entries = Object.entries(obj)
  32.       const split = splitAtLast(regex,":")
  33.       label = split[1]
  34.       lift = label === "^"
  35.       if (lift) label = false
  36.       regex = split[0]
  37.       regex = new RegExp(regex)
  38.       output = entries.filter(([key]) => key.match(regex))
  39.         .map(e => {
  40.           if (label){
  41.             return [e[1][label],queryOnlyObj(e[1],rest)]
  42.           } else {
  43.             return [e[0],queryOnlyObj(e[1],rest)]
  44.           }
  45.         })
  46.         .filter(x=>x[1]!==undefined)
  47.     }
  48.     switch (type) {
  49.       case "{" :
  50.         //expand regex, need to use var here because there's only one scope per switch
  51.         return output.reduce(reduceToObj, lift?[]:{})
  52.         break
  53.       case "}" :
  54.         //collect regex
  55.         //[[key,value],...]
  56.         if (lift){
  57.           return output.reduce((carry,obj) => {
  58.             let entries = Object.entries(obj[1])
  59.             entries.forEach(e => {
  60.               if (!carry[e[0]]){
  61.                 carry[e[0]] = []
  62.               }
  63.               carry[e[0]].push(e[1])
  64.             })
  65.             return carry
  66.           }, {})
  67.         } else {
  68.           return output.reduce((carry,obj) => {
  69.             let entries = Object.entries(obj[1])
  70.             entries.forEach(e => {
  71.               if (!carry[e[0]]){
  72.                 carry[e[0]] = []
  73.               }
  74.               carry[e[0]].push({[obj[0]]:e[1]})
  75.             })
  76.             return carry
  77.           }, {})
  78.         }
  79.         break
  80.       default:
  81.         return queryOnlyObj(obj[key],rest)
  82.         break
  83.     }
  84.   }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement