Last active
January 15, 2020 03:50
-
-
Save sungchuni/010760e9e5b9ab5ab71881ae617ce6c6 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
const _ = { | |
uniq: require("lodash/uniq"), | |
unzip: require("lodash/unzip") | |
}; | |
module.exports.decompileRoutePath = function decompileRoutePath(paths, ids) { | |
const parsedPaths = paths.map(path => | |
path.replace(/^\/+|\/+$/g, "").split("/") | |
); | |
if ( | |
!parsedPaths | |
.map(({ length }) => length) | |
.every((len, index, pathTokensLengthOfPaths) => | |
pathTokensLengthOfPaths.every(_len => _len === len) | |
) | |
) { | |
throw new Error("path tokens length in each path must be same"); | |
} | |
if ( | |
!parsedPaths.every(parsedPath => parsedPath.every(pathToken => pathToken)) | |
) { | |
throw new Error("all the path tokens in each path must be not empty"); | |
} | |
const paramValues = _.unzip(parsedPaths).map(grouped => | |
_.uniq(grouped).length > 1 ? grouped : false | |
); | |
const paramIdValues = {}; | |
const routePaths = parsedPaths.map((pathTokens, parsedPathIndex) => { | |
const idsConsumer = (function*(ids) { | |
let i = -1; | |
while (true) yield ids[++i] || ids[(i = 0)]; | |
})(ids || ["id"]); | |
const paramIds = []; | |
let modifier = 0; | |
const routeTokens = pathTokens.map((pathToken, pathTokenIndex) => { | |
if (paramValues[pathTokenIndex][parsedPathIndex]) { | |
const currentId = idsConsumer.next().value; | |
const paramId = paramIds.includes(currentId) | |
? `${currentId}${++modifier}` | |
: currentId; | |
paramIds.push(paramId); | |
(paramIdValues[paramId] || (paramIdValues[paramId] = [])).push( | |
pathToken | |
); | |
return `:${paramId}`; | |
} else { | |
return pathToken; | |
} | |
}); | |
return `/${routeTokens.join("/")}`; | |
}); | |
return { | |
routePath: routePaths[0], | |
paramIdValues | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment