1
+ import { isObject } from './is'
2
+
1
3
/**
2
4
* Replace backslash to slash
3
5
*
@@ -31,6 +33,8 @@ export function ensureSuffix(suffix: string, str: string) {
31
33
32
34
/**
33
35
* Dead simple template engine, just like Python's `.format()`
36
+ * Support passing variables as either in index based or object/name based approach
37
+ * While using object/name based approach, you can pass a fallback value as the third argument
34
38
*
35
39
* @category String
36
40
* @example
@@ -41,14 +45,38 @@ export function ensureSuffix(suffix: string, str: string) {
41
45
* 'Anthony'
42
46
* ) // Hello Inès! My name is Anthony.
43
47
* ```
48
+ *
49
+ * ```
50
+ * const result = namedTemplate(
51
+ * '{greet}! My name is {name}.',
52
+ * { greet: 'Hello', name: 'Anthony' }
53
+ * ) // Hello! My name is Anthony.
54
+ * ```
55
+ *
56
+ * * const result = namedTemplate(
57
+ * '{greet}! My name is {name}.',
58
+ * { greet: 'Hello' }, // name isn't passed hence fallback will be used for name
59
+ * 'placeholder'
60
+ * ) // Hello! My name is placeholder.
61
+ * ```
44
62
*/
63
+ export function template ( str : string , object : Record < string | number , any > , fallback ?: string | ( ( key : string ) => string ) ) : string
64
+ export function template ( str : string , ...args : ( string | number | BigInt | undefined | null ) [ ] ) : string
45
65
export function template ( str : string , ...args : any [ ] ) : string {
46
- return str . replace ( / { ( \d + ) } / g, ( match , key ) => {
47
- const index = Number ( key )
48
- if ( Number . isNaN ( index ) )
49
- return match
50
- return args [ index ]
51
- } )
66
+ const [ firstArg , fallback ] = args
67
+
68
+ if ( isObject ( firstArg ) ) {
69
+ const vars = firstArg as Record < string , any >
70
+ return str . replace ( / { ( [ \w \d ] + ) } / g, ( _ , key ) => vars [ key ] || ( ( typeof fallback === 'function' ? fallback ( key ) : fallback ) ?? key ) )
71
+ }
72
+ else {
73
+ return str . replace ( / { ( \d + ) } / g, ( _ , key ) => {
74
+ const index = Number ( key )
75
+ if ( Number . isNaN ( index ) )
76
+ return key
77
+ return args [ index ]
78
+ } )
79
+ }
52
80
}
53
81
54
82
// port from nanoid
0 commit comments