All files / url setQuery.ts

100% Statements 24/24
100% Branches 6/6
100% Functions 5/5
100% Lines 24/24

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 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 60 61 62 63 64 65 66 67 68                                          1x 10x 1x   9x 9x 9x 9x   9x   10x 10x 10x   6x   10x         9x 12x   1x   11x       9x   1x   8x 12x   8x     9x       1x  
/**
 * 将参数设置到 location.search 上
 * @method setQuery
 * @param {String} url URL字符串
 * @param {Object} query 参数对象
 * @return {String} 拼接好参数的URL字符串
 * @example
 * import { setQuery } from '@spore-ui/tskit';
 * setQuery('localhost'); // 'localhost'
 * setQuery('localhost', {a: 1}); // 'localhost?a=1'
 * setQuery('', {a: 1}); // '?a=1'
 * setQuery('localhost?a=1', {a: 2}); // 'localhost?a=2'
 * setQuery('localhost?a=1', {a: ''}); // 'localhost?a='
 * setQuery('localhost?a=1', {a: null}); // 'localhost'
 * setQuery('localhost?a=1', {b: 2}); // 'localhost?a=1&b=2'
 * setQuery('localhost?a=1&b=1', {a: 2, b: 3}); // 'localhost?a=2&b=3'
 * setQuery('localhost#a=1', {a: 2, b: 3}); // 'localhost?a=2&b=3#a=1'
 * setQuery('#a=1', {a: 2, b: 3}); // '?a=2&b=3#a=1'
 */
import { TypePlainObject } from '../types';
 
export function setQuery(href: string, query?: TypePlainObject): string {
  const url = href || '';
  if (!query) { return url; }
 
  const reg = /([^?#]*)(\?{0,1}[^?#]*)(#{0,1}.*)/;
  return url.replace(reg, (match, path, strSearch, hash) => {
    let search = strSearch || '';
    search = search.replace(/^\?/, '');
 
    const para = search.split('&').reduce(
      (item: TypePlainObject, pair: string) => {
        const obj = item;
        const arr = pair.split('=');
        const [key] = arr;
        if (key) {
          [, obj[key]] = arr;
        }
        return obj;
      },
      {},
    );
 
    Object.keys(query).forEach((key) => {
      const value = query[key];
      if (value === null || typeof value === 'undefined') {
        delete para[key];
      } else {
        para[key] = value;
      }
    });
 
    const paraKeys = Object.keys(para);
    if (!paraKeys.length) {
      search = '';
    } else {
      const strQuery = paraKeys
        .map((key) => `${key}=${para[key]}`)
        .join('&');
      search = `?${strQuery}`;
    }
 
    return `${path}${search}${hash}`;
  });
}
 
export default setQuery;