All files / src/domain/createBuildRoute index.js

96.43% Statements 27/28
93.33% Branches 14/15
100% Functions 7/7
96.3% Lines 26/27
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59        19x 23x 23x 23x 23x 23x       23x       23x 6x     17x 9x     8x       21x 21x 27x       27x     21x       40x 40x 56x 56x 40x     16x   40x 40x   40x        
import is from 'is_js';
 
import { formatPattern } from 'react-router';
 
export const createBuildRoute = (ownProps) => (...args) => {
  const route = getRoute(args);
  const params = getParams(args);
  const root = /^\//.test(route) ? '/' : getRoot(ownProps.routes);
  const finalParams = Object.assign({}, ownProps.params, params);
  return normalizeUrl(formatPattern(`/${root}/${route}`, finalParams));
};
 
function getRoute(args) {
  return is.string(args[0]) ? args[0] : '';
}
 
function getParams(args) {
  if (args.length === 1 && is.object(args[0])) {
    return args[0];
  }
 
  if (args.length > 1) {
    return args[1];
  }
 
  return undefined;
}
 
function getRoot(routes = []) {
  let newRoute = '';
  routes.forEach((routePiece) => {
    Iif (is.not.string(routePiece.path)) {
      return;
    }
 
    newRoute = `${newRoute}/${routePiece.path}`;
  });
 
  return newRoute;
}
 
export function normalizeUrl(url) {
  let result = url.replace(/(^|[\w-])\/+/gi, '$1/'); // Gets rid of duplicated slashes (//)
  while (true) { // Interprets two dots (..), going up in the path for each occurrence
    const newResult = result.replace(/((^\/)|[\w-]*\/)\.\.\/?/gi, '$2');
    if (result === newResult) {
      break;
    }
 
    result = newResult;
  }
  result = result.replace(/(\/\.|\.\/)/g, ''); // Gets rid of ./
  result = result.replace(/\/$/, '');
 
  return result;
}
 
export default createBuildRoute;