|
| 1 | +/** |
| 2 | + * @file extToValue |
| 3 | + * @module pathe/lib/extToValue |
| 4 | + */ |
| 5 | + |
| 6 | +import basename from '#lib/basename' |
| 7 | +import dot from '#lib/dot' |
| 8 | +import type { EmptyString, Ext } from '@flex-development/pathe' |
| 9 | + |
| 10 | +/** |
| 11 | + * Get a value for `input` based on its file extension. |
| 12 | + * |
| 13 | + * This algorithm picks the value with the longest matching file extension, |
| 14 | + * so if `map` has the keys `'.mts'` and `'.d.mts'`, the value for `'.d.mts'` |
| 15 | + * will be returned. |
| 16 | + * |
| 17 | + * @see {@linkcode EmptyString} |
| 18 | + * @see {@linkcode Ext} |
| 19 | + * |
| 20 | + * @category |
| 21 | + * utils |
| 22 | + * |
| 23 | + * @template {any} T |
| 24 | + * Map value |
| 25 | + * |
| 26 | + * @this {void} |
| 27 | + * |
| 28 | + * @param {URL | string} input |
| 29 | + * The {@linkcode URL}, URL string, or path to handle |
| 30 | + * @param {Partial<Record<EmptyString | Ext, T>>} map |
| 31 | + * Extension map |
| 32 | + * @return {T | undefined} |
| 33 | + * Value based on file extension of `input` |
| 34 | + */ |
| 35 | +function extToValue<T>( |
| 36 | + this: void, |
| 37 | + input: URL | string, |
| 38 | + map: Partial<Record<EmptyString | Ext, T>> |
| 39 | +): T | undefined { |
| 40 | + /** |
| 41 | + * Basename to check. |
| 42 | + * |
| 43 | + * @var {string} base |
| 44 | + */ |
| 45 | + let base: string = basename(input) |
| 46 | + |
| 47 | + /** |
| 48 | + * Index of {@linkcode dot}. |
| 49 | + * |
| 50 | + * @var {number} index |
| 51 | + */ |
| 52 | + let index: number = base.indexOf(dot) |
| 53 | + |
| 54 | + /** |
| 55 | + * Current value. |
| 56 | + * |
| 57 | + * @var {T | undefined} value |
| 58 | + */ |
| 59 | + let value: T | undefined |
| 60 | + |
| 61 | + if (index === -1) { |
| 62 | + value = map[''] |
| 63 | + } else { |
| 64 | + while (true) { |
| 65 | + value = map[base.slice(index) as EmptyString | Ext] |
| 66 | + |
| 67 | + if (value === undefined) { |
| 68 | + base = base.slice(index + 1) |
| 69 | + |
| 70 | + /** |
| 71 | + * Next index of {@linkcode dot}. |
| 72 | + * |
| 73 | + * @const {number} nextIndex |
| 74 | + */ |
| 75 | + const nextIndex: number = base.indexOf(dot) |
| 76 | + |
| 77 | + if (nextIndex !== -1) { |
| 78 | + index = nextIndex |
| 79 | + continue |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + break |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return value |
| 88 | +} |
| 89 | + |
| 90 | +export default extToValue |
0 commit comments