URLSearchParams

源码

https://github.com/ddzy/ts-utility-plugins/tree/master/src/ddzy/utility/algorithm/url-search-params

说明

前天在掘金看到一篇文章: https://juejin.im/post/5d038c9051882548ac439933#comment

里面有提到URLSearchParams 这个小东西, 索性就实现一下它.

源码地址: https://github.com/ddzy/ts-utility-plugins/tree/master/src/ddzy/utility/algorithm/url-search-params

用法

index.ts
const usp = new utilityAlgorithm.URLSearchParams({});
// ? handleAppend
usp.handleAppend('skill', 'programmer');
usp.handleAppend('name', 'duan');
// ? handleDelete
usp.handleDelete('age');
usp.handleDelete('name');
usp.handleDelete('isSelf');
// ? handleGet
const u1 = usp.handleGet('');
const u2 = usp.handleGet('name');
const u3 = usp.handleGet('skill');
const u4 = usp.handleGet('age');
console.log({
u1,
u2,
u3,
u4,
});
// ? handleGetAll
const u1 = usp.handleGetAll();
console.log(u1);
// ? handleHas
const u1 = usp.handleHas('name');
const u2 = usp.handleHas('skill');
const u3 = usp.handleHas('');
console.log({
u1,
u2,
u3,
});
// ? handleSet
usp.handleSet('name', 'duanzhaoyang');
usp.handleSet('age', 20);
usp.handleSet('isSelf', false);
usp.handleAppend('age', 30).handleAppend('age', 40);
usp.handleSet('age', 80);
// ? handleKeys
const u1 = usp.handleKeys();
console.log(u1);
// ? handleValues
const u1 = usp.handleValues();
console.log(u1);
usp.handleAppend('skill', 'programmer');
const u2 = usp.handleValues();
console.log(u2);
// ? iterator
for (const v of (usp.state.params as any)) {
console.log(v);
}
for (const [v, i] of (usp.state.params as any)) {
console.log(v, i);
}
console.log(usp.state);

API

常用接口

types.ts
export interface IURLSearchParamsProps {
url?: string;
};
export interface IURLSearchParamsState {
url: string;
params: IStaticParams;
};
export type IStaticParams = Record<IStaticParamsKey, IStaticParamsValue>;
export type IStaticParamsKey = string | symbol;
export type IStaticParamsValue = string | number | boolean | Function;

方法列表

Name

Value

Description

handleAppend

(key: IStaticParamsKey, value: IStaticParamsValue) => URLSearchParams

追加新的键值对

handleDelete

(key: IStaticParamsKey) => URLSearchParams

移除某个键值对

handleGet

(key: IStaticParamsKey) => IStaticParamsValue | null

获取指定的参数键值

handleGetAll

() => [IStaticParamsKey, IStaticParamsValue][]

获取所有的参数值

handleHas

(key: IStaticParamsKey) => boolean

判断是否存在指定键名

handleSet

(key: IStaticParamsKey, value: IStaticParamsValue) => URLSearchParams

更新url中的对应键值(但是params中的值是不变的)

handleKeys

() => IStaticParamsKey[]

获取键名数组

handleValues

() => IStaticParamsValue[]

获取键值数组