-
-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathparse-as-tuple.ts
More file actions
74 lines (72 loc) · 2.33 KB
/
Copy pathparse-as-tuple.ts
File metadata and controls
74 lines (72 loc) · 2.33 KB
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
import { createParser, type SingleParserBuilder } from 'nuqs'
import { safeParse } from 'nuqs/lib'
type ParserTuple<T extends readonly unknown[]> = {
[K in keyof T]: SingleParserBuilder<T[K]>
} & { length: 2 | 3 | 4 | 5 | 6 | 7 | 8 }
/**
* Parse a comma-separated tuple with type-safe positions.
* Items are URI-encoded for safety, so they may not look nice in the URL.
* allowed tuple length is 2-8.
*
* @param itemParsers Tuple of parsers for each position in the tuple
* @param separator The character to use to separate items (default ',')
*/
export function parseAsTuple<T extends any[]>(
itemParsers: ParserTuple<T>,
separator = ','
): SingleParserBuilder<T> {
const encodedSeparator = encodeURIComponent(separator)
if (itemParsers.length < 2 || itemParsers.length > 8) {
throw new Error(
`Tuple length must be between 2 and 8, got ${itemParsers.length}`
)
}
return createParser<T>({
parse: query => {
if (query === '') {
return null
}
const parts = query.split(separator)
if (parts.length < itemParsers.length) {
return null
}
// iterating by parsers instead of parts, any additional parts are ignored.
const result = itemParsers.map(
(parser, index) =>
safeParse(
parser.parse,
parts[index]!.replaceAll(encodedSeparator, separator),
`[${index}]`
) as T[number] | null
)
return result.some(x => x === null) ? null : (result as T)
},
serialize: (values: T) => {
if (values.length !== itemParsers.length) {
throw new Error(
`Tuple length mismatch: expected ${itemParsers.length}, got ${values.length}`
)
}
return values
.map((value, index) => {
const parser = itemParsers[index]!
const str = parser.serialize ? parser.serialize(value) : String(value)
return str.replaceAll(separator, encodedSeparator)
})
.join(separator)
},
eq(a: T, b: T) {
if (a === b) {
return true
}
if (a.length !== b.length || a.length !== itemParsers.length) {
return false
}
return a.every((value, index) => {
const parser = itemParsers[index]!
const itemEq = parser.eq ?? ((x, y) => x === y)
return itemEq(value, b[index])
})
}
})
}