返回 slidev
utils.ts
根目录 / packages / parser / src / utils.ts
1 import { isNumber, range, uniq } from '@antfu/utils'
2
3 export * from './timesplit'
4
5 const RE_ASPECT_RATIO_SEPARATOR = /[:/x|]/
6
7 /**
8 * 1,3-5,8 => [1, 3, 4, 5, 8]
9 */
10 export function parseRangeString(total: number, rangeStr?: string) {
11 if (!rangeStr || rangeStr === 'all' || rangeStr === '*')
12 return range(1, total + 1)
13
14 if (rangeStr === 'none')
15 return []
16
17 const indexes: number[] = []
18 for (const part of rangeStr.split(/[,;]/g)) {
19 if (!part.includes('-')) {
20 indexes.push(+part)
21 }
22 else {
23 const [start, end] = part.split('-', 2)
24 indexes.push(
25 ...range(+start, !end
26 ? (total + 1)
27 : (+end + 1)),
28 )
29 }
30 }
31
32 return uniq(indexes).filter(i => i <= total).sort((a, b) => a - b)
33 }
34
35 /**
36 * Accepts `16/9` `1:1` `3x4`
37 */
38 export function parseAspectRatio(str: string | number) {
39 if (isNumber(str))
40 return str
41 if (!Number.isNaN(+str))
42 return +str
43 const [wStr = '', hStr = ''] = str.split(RE_ASPECT_RATIO_SEPARATOR)
44 const w = Number.parseFloat(wStr.trim())
45 const h = Number.parseFloat(hStr.trim())
46
47 if (Number.isNaN(w) || Number.isNaN(h) || h === 0)
48 throw new Error(`Invalid aspect ratio "${str}"`)
49
50 return w / h
51 }
52
52 lines TYPESCRIPT