@fe-free/tool 1.1.2 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @fe-free/tool
2
2
 
3
+ ## 1.1.4
4
+
5
+ ## 1.1.3
6
+
7
+ ### Patch Changes
8
+
9
+ - feat: add url
10
+
3
11
  ## 1.1.2
4
12
 
5
13
  ## 1.1.1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fe-free/tool",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "description": "",
5
5
  "main": "./src/index.ts",
6
6
  "author": "",
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  export { pinyin, pinyinFilter, pinyinMatch, pinyinMatchWithoutFirstLetter } from './pinyin';
2
2
 
3
3
  export { getDayjs } from './date';
4
+
5
+ export { buildURL } from './url';
@@ -0,0 +1,48 @@
1
+ type SearchParamsLike = Record<string, any> | URLSearchParams | string;
2
+
3
+ function mergeSearchParams(l, r) {
4
+ const lsp = new URLSearchParams(l);
5
+ const rsp = new URLSearchParams(r);
6
+
7
+ return new URLSearchParams(`${lsp.toString()}&${rsp.toString()}`);
8
+ }
9
+
10
+ interface BuildUrlOptions {
11
+ searchParams?: SearchParamsLike;
12
+ hashSearchParams?: SearchParamsLike;
13
+ }
14
+ // http://xxxx/a/b/c?d=1&e=2?#f/g/h?i=3&j=4
15
+ // path searchParams hash
16
+ function buildURL(url: string, options?: BuildUrlOptions) {
17
+ const { searchParams, hashSearchParams } = options || {};
18
+
19
+ const newURL = new URL(url);
20
+
21
+ // 如果提供则合并
22
+ if (searchParams) {
23
+ const newSP = mergeSearchParams(newURL.searchParams, searchParams);
24
+ newURL.search = `?${newSP.toString()}`;
25
+ }
26
+
27
+ if (hashSearchParams) {
28
+ // 转换成 URLSearchParams
29
+ const hashSP = new URLSearchParams(hashSearchParams);
30
+ const hash = newURL.hash;
31
+ const index = hash.indexOf('?');
32
+
33
+ // 存在问号
34
+ if (index > -1) {
35
+ // merge
36
+ const newHashSP = mergeSearchParams(hash.slice(index + 1), hashSP);
37
+ newURL.hash = `${hash.slice(0, index)}?${newHashSP.toString()}`;
38
+ }
39
+ // 没有问号
40
+ else {
41
+ newURL.hash = `${hash}?${hashSP.toString()}`;
42
+ }
43
+ }
44
+
45
+ return newURL.toString();
46
+ }
47
+
48
+ export { buildURL };