-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.ts
More file actions
66 lines (54 loc) · 1.7 KB
/
Copy pathmod.ts
File metadata and controls
66 lines (54 loc) · 1.7 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
type Printable = string | number | undefined | null;
type Printables = Printable | Printables[];
type TemplateStringsArguments = [strings: TemplateStringsArray, ...values: Printables[]];
/**
* TODO: What single character can I use instead?
* TODO: Wait for promises to render?
*
* Template string method which provides common templating features not available in JS:
* - undefined & null is converted to ''
* - Arrays are joined without seperator
*/
export function template(strings: TemplateStringsArray | TemplateStringsArguments, ...values: Printables[]): string {
// Normalize arguments in case they come from a "regular" function call
if(Array.isArray(strings[0])){
// @ts-ignore
[strings, ...values] = strings;
}
let acc = '';
for (let i = 0; i < strings.length; i++) {
acc += strings[i];
if (Array.isArray(values[i])) {
acc += (values[i] as Printables[])
.map(value => value ?? '')
.join('');
} else {
acc += (values[i] ?? '');
}
}
return acc;
}
export function print(text: Printable, defaultText: string = '') {
return !!text
? text
: defaultText;
}
type LoopState = {
isFirst: boolean,
isLast: boolean,
};
type LoopCallback = <I>(item:I, state:LoopState)=>string;
export const loop = <I>(list:I[], callback:LoopCallback):string => {
let acc = '';
const state:LoopState = {
isFirst: true,
isLast: false,
};
for (let i = 0; i < list.length; i++) {
const item:I = list[i];
state.isLast = i === list.length - 1;
acc += callback<I>(item, state);
state.isFirst = false;
}
return acc;
};