Created
June 14, 2020 21:36
-
-
Save Jabher/5e4d01a6a3d7d675b2add89e9dc01b7b to your computer and use it in GitHub Desktop.
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
import { Chunk, ParamType } from './pathParser' | |
import { last } from 'ramda' | |
const evalCache = Object.create(null) | |
const cachedEval = (fn: string): (path: string[]) => {} => { | |
if (!evalCache[fn]) { | |
/* see MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval | |
* from the line "If you use the eval function indirectly..." | |
**/ | |
const globalEval = eval | |
evalCache[fn] = globalEval(`(function magicCreateParams (path) {return {${fn}}})`) | |
} | |
return evalCache[fn] | |
} | |
function emptyFn () { | |
return {} | |
} | |
export const createParamsConstructor = (pathChunks: Chunk[]) => { | |
const pathKey = 'path' | |
const keys = pathChunks | |
.map(({ chunk, type }, index) => type === ParamType.param ? { chunk, index } : null) | |
.filter(val => val !== null) | |
.map(({ chunk, index }) => `${chunk}: ${pathKey}[${index}]`) | |
.join(',') | |
if (keys.length === 0) { | |
return emptyFn | |
} | |
if (last(pathChunks).type === ParamType.wildcard) { | |
const tail = pathChunks.length - 1 | |
const restKey = last(pathChunks).chunk || '_' | |
return cachedEval(`${keys}, ${restKey}: path.slice(0, ${tail}).join('/')`) | |
} else { | |
return cachedEval(`${keys}`) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment