-
Notifications
You must be signed in to change notification settings - Fork 1
/
strWhen.ts
47 lines (45 loc) · 1.25 KB
/
strWhen.ts
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
/**
* Apply the callback's string changes if the given "value" is truthy.
*
* @param {boolean | unknown} condition - Determine if the callback should be called
* @param {unknown} instance - The target value
* @param {function} callback - The function to be called upon the condition truthyness
* @param {function} [fallback] - The function to be called upon the condition falsyness
* @returns {unknown}
*
* @example
* ```js
* strWhen(true, 'hello', (instance, condition) => {
* console.log(instance, condition); // 'hello', true
* }); // 'hello'
*
* strWhen(true, 'hello', (instance, condition) => {
* return 'bye';
* }); // 'bye'
*
* strWhen(
* false,
* 'hello',
* (instance, condition) => {
* return 'bye';
* },
* (instance, condition) => {
* return 'from fallback';
* }
* ); // 'from fallback'
* ```
*/
export default function strWhen<C, I>(
condition: C,
instance: I,
callback: (instance: I, condition: C) => I | unknown,
fallback?: (instance: I, condition: C) => I | unknown
): I | unknown {
if (condition) {
return callback(instance, condition) ?? instance;
}
if (fallback) {
return fallback(instance, condition) ?? instance;
}
return instance;
}