-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ext-to-value.mts
90 lines (79 loc) · 1.74 KB
/
ext-to-value.mts
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
/**
* @file extToValue
* @module pathe/lib/extToValue
*/
import basename from '#lib/basename'
import dot from '#lib/dot'
import type { EmptyString, Ext } from '@flex-development/pathe'
/**
* Get a value for `input` based on its file extension.
*
* This algorithm picks the value with the longest matching file extension,
* so if `map` has the keys `'.mts'` and `'.d.mts'`, the value for `'.d.mts'`
* will be returned.
*
* @see {@linkcode EmptyString}
* @see {@linkcode Ext}
*
* @category
* utils
*
* @template {any} T
* Map value
*
* @this {void}
*
* @param {URL | string} input
* The {@linkcode URL}, URL string, or path to handle
* @param {Partial<Record<EmptyString | Ext, T>>} map
* Extension map
* @return {T | undefined}
* Value based on file extension of `input`
*/
function extToValue<T>(
this: void,
input: URL | string,
map: Partial<Record<EmptyString | Ext, T>>
): T | undefined {
/**
* Basename to check.
*
* @var {string} base
*/
let base: string = basename(input)
/**
* Index of {@linkcode dot}.
*
* @var {number} index
*/
let index: number = base.indexOf(dot)
/**
* Current value.
*
* @var {T | undefined} value
*/
let value: T | undefined
if (index === -1) {
value = map['']
} else {
while (true) {
value = map[base.slice(index) as EmptyString | Ext]
if (value === undefined) {
base = base.slice(index + 1)
/**
* Next index of {@linkcode dot}.
*
* @const {number} nextIndex
*/
const nextIndex: number = base.indexOf(dot)
if (nextIndex !== -1) {
index = nextIndex
continue
}
}
break
}
}
return value
}
export default extToValue