From 8d14dcb7d15786d4c12f9ffa2c6d90c71a75acbe Mon Sep 17 00:00:00 2001 From: Baldur Helgason Date: Tue, 16 Jul 2019 19:16:47 +0000 Subject: [PATCH] perf: optimise url handling (#414) --- src/constructUrl.js | 22 +++++++++++++++------- src/extractQueryParams.js | 26 ++++++++++++++++---------- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/src/constructUrl.js b/src/constructUrl.js index c62d01ae..8038f4fe 100644 --- a/src/constructUrl.js +++ b/src/constructUrl.js @@ -106,9 +106,14 @@ var DEFAULT_OPTIONS = Object.freeze({ }); function constructUrlFromParams(src, params) { - return `${src}?${Object.entries(params) - .map(([a, b]) => `${a}=${encodeURIComponent(b)}`) - .join("&")}`; + const keys = Object.keys(params); + const keysLength = keys.length; + let url = src + "?"; + for (let i = 0; i < keysLength; i++) { + const key = keys[i]; + url += key + "=" + encodeURIComponent(params[key]) + "&"; + } + return url.slice(0, -1); } /** @@ -123,9 +128,12 @@ function constructUrl(src, longOptions) { return ""; } - var shortOptions = Object.assign({}, DEFAULT_OPTIONS); - Object.keys(longOptions).forEach(function(key) { - var val = longOptions[key]; + const shortOptions = Object.assign({}, DEFAULT_OPTIONS); + const keys = Object.keys(longOptions); + const keysLength = keys.length; + for (let i = 0; i < keysLength; i++) { + let key = keys[i]; + let val = longOptions[key]; if (PARAM_EXPANSION[key]) { key = PARAM_EXPANSION[key]; @@ -138,7 +146,7 @@ function constructUrl(src, longOptions) { } shortOptions[key] = val; - }); + } return constructUrlFromParams(src, shortOptions); } diff --git a/src/extractQueryParams.js b/src/extractQueryParams.js index 71614ff5..351f41cf 100644 --- a/src/extractQueryParams.js +++ b/src/extractQueryParams.js @@ -1,13 +1,19 @@ export default function extractQueryParams(src) { - const [url, query] = src.split("?"); - const params = query - ? query - .split("&") - .map(x => { - const [key, val] = x.split("="); - return [key, decodeURIComponent(val)]; - }) - .reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {}) - : {}; + const splitSrc = src.split("?"); + const url = splitSrc[0]; + const query = splitSrc[1]; + if (!query) { + return [url, {}]; + } + const paramsPairs = query.split("&"); + const params = {}; + const len = paramsPairs.length; + for (let i = 0; i < len; i++) { + const param = paramsPairs[i]; + const splitParam = param.split("="); + const key = splitParam[0]; + const val = splitParam[1]; + params[key] = decodeURIComponent(val); + } return [url, params]; }