UNPKG

react-enroute

Version:
108 lines (99 loc) 2.7 kB
"use strict"; exports.__esModule = true; exports.findPath = findPath; exports.findPathValue = findPathValue; exports.loc = exports.genLocation = genLocation; exports.isPath = isPath; var _pathToRegexp = require("path-to-regexp"); /** * Generate location based on path and params * @alias loc * genLocation('/users/:id', {id: '42'}) => '/users/42' * * @param {string} path * @param {object?} params * @param {object=} options - [path-to-regexp](https://github.com/pillarjs/path-to-regexp#usage) options * @return {string} */ function genLocation(path, params, options) { if (!path) return ''; return (0, _pathToRegexp.compile)(path, options)(params); } /** * Check if location matches path * * isPath('/users/:id', '/users/42') => true * * @param {string} path * @param {string} location * @param {object=} options - [path-to-regexp](https://github.com/pillarjs/path-to-regexp#usage) options * @return {boolean} */ function isPath(path, location, options) { return !!(0, _pathToRegexp.pathToRegexp)(path, null, options).exec(location); } /** * Search path * * findPath(['/users', '/users/:id'], '/users/42') => { * path: '/users/:id, * params: {id: '42'}, * } * * @typedef SearchResult * @property {string} path * @property {object} params * * @param {[string]} paths * @param {string} location * @param {object} options - [path-to-regexp](https://github.com/pillarjs/path-to-regexp#usage) options * @return {SearchResult|undefined} */ function findPath(paths, location, options) { for (var i = 0; i < paths.length; i++) { var path = paths[i]; var result = (0, _pathToRegexp.match)(path, options)(location); if (!result) continue; var params = result.params; return { path: path, params: params }; } } /** * Search over object whose keys are paths * * findPathValue({ * '/users': UserListToolbar, * '/users/:id': UserToolbar, * }, '/users/42') * => { * path: '/users/:id', * value: UserToolbar, * params: {id: '42'}, * } * * @typedef SearchValueResult * @property {string} path * @property {*} value * @property {object} params * * @param {object} obj - keys are paths and values can be any * @param {string} location * @param {object=} options - [path-to-regexp](https://github.com/pillarjs/path-to-regexp#usage) options * @return {SearchValueResult|undefined} */ function findPathValue(obj, location, options) { for (var path in obj) { var result = (0, _pathToRegexp.match)(path, options)(location); if (!result) continue; var value = obj[path]; var params = result.params; return { path: path, value: value, params: params }; } }