Skip to content

Instantly share code, notes, and snippets.

@nayeemzen
Created October 23, 2018 18:41
Show Gist options
  • Select an option

  • Save nayeemzen/9ef872d75a6147c56586bf0f2f37b32b to your computer and use it in GitHub Desktop.

Select an option

Save nayeemzen/9ef872d75a6147c56586bf0f2f37b32b to your computer and use it in GitHub Desktop.

Revisions

  1. Nayeem Zen created this gist Oct 23, 2018.
    16 changes: 16 additions & 0 deletions functional-query-string-parser.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    // Functional programming approach to parsing query strings in Typescript/ES6.
    function parseQueryString(search: string) {
    return (search.startsWith('?') ? search.substring(1) : search)
    .split('&')
    .map(str => {
    const eqIdx = str.indexOf('=');
    if (eqIdx <= 0 || eqIdx >= str.length - 1) {
    return {};
    }

    const key = str.substring(0, eqIdx);
    const value = str.substring(eqIdx + 1, str.length);
    return {[key]: value};
    })
    .reduce((prev, next) => ({...prev, ...next}));
    }