All files / lib query.js

100% Statements 17/17
87.5% Branches 7/8
100% Functions 5/5
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 301x 1x 1x 1x 1x   1x 6x 6x 2x     6x   4x     1x 6x         5x 5x   5x      
const QUERY_PREFIX = '?';
const AMPERSAND = '&';
const EQUALS = '=';
const EMPTY = '';
const EMPTY_QUERY = {};
 
export const toQueryString = (query = {}) => {
    const keys = Object.keys(query);
    if (keys.length == 0) {
        return EMPTY;
    }
 
    const q = QUERY_PREFIX + (keys.map(k =>  k + EQUALS + query[k] + AMPERSAND).join(EMPTY));
 
    return q.endsWith(AMPERSAND) ? q.substr(0, q.length -1) : q;
};
 
export const parseQuery = (queryString = '') => {
    return queryString.length > 1 ?
        queryString
            .replace(QUERY_PREFIX, EMPTY)
            .split(AMPERSAND)
            .map(couple => {
                const split = couple.split(EQUALS);
                return { [split[0]]: split[1] };
            })
            .reduce((acc, param) => ({ ...acc, ...param }), {}) :
        EMPTY_QUERY;
}