-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathutils.ts
100 lines (87 loc) · 1.91 KB
/
utils.ts
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import type { Storage, StorageValue } from "./types";
type StorageKeys = Array<keyof Storage>;
const storageKeyProperties: StorageKeys = [
"has",
"hasItem",
"get",
"getItem",
"getItemRaw",
"set",
"setItem",
"setItemRaw",
"del",
"remove",
"removeItem",
"getMeta",
"setMeta",
"removeMeta",
"getKeys",
"clear",
"mount",
"unmount",
];
export function prefixStorage<T extends StorageValue>(
storage: Storage<T>,
base: string
): Storage<T> {
base = normalizeBaseKey(base);
if (!base) {
return storage;
}
const nsStorage: Storage<T> = { ...storage };
for (const property of storageKeyProperties) {
// @ts-ignore
nsStorage[property] = (key = "", ...args) =>
// @ts-ignore
storage[property](base + key, ...args);
}
nsStorage.getKeys = (key = "", ...arguments_) =>
storage
.getKeys(base + key, ...arguments_)
// Remove Prefix
.then((keys) => keys.map((key) => key.slice(base.length)));
return nsStorage;
}
export function normalizeKey(key?: string) {
if (!key) {
return "";
}
return (
key
.split("?")[0]
?.replace(/[/\\]/g, ":")
.replace(/:+/g, ":")
.replace(/^:|:$/g, "") || ""
);
}
export function joinKeys(...keys: string[]) {
return normalizeKey(keys.join(":"));
}
export function normalizeBaseKey(base?: string) {
base = normalizeKey(base);
return base ? base + ":" : "";
}
export function filterKeyByDepth(
key: string,
depth: number | undefined
): boolean {
if (depth === undefined) {
return true;
}
let substrCount = 0;
let index = key.indexOf(":");
while (index > -1) {
substrCount++;
index = key.indexOf(":", index + 1);
}
return substrCount <= depth;
}
export function filterKeyByBase(
key: string,
base: string | undefined
): boolean {
if (base) {
return key.startsWith(base) && key[key.length - 1] !== "$";
}
return key[key.length - 1] !== "$";
}