@@ -32,52 +32,52 @@ export function stringInterpolation<
32
32
string : string ,
33
33
variables : Record < PropertyKey , VariableValue > ,
34
34
{
35
- pattern = new RegExp ( / \{ { ( [ ^ { ] + ) } } / g) ,
35
+ pattern = / \{ { ( [ ^ { ] + ) } } / g,
36
36
sanity = true ,
37
- raw : rawOutput = false ,
37
+ raw = false ,
38
38
} : StringInterpolationOptions < OptionRaw > = { } ,
39
39
) : StringInterpolationReturn < VariableValue , OptionRaw > {
40
40
if ( ! string && sanity ) throw new Error ( "Empty string" )
41
41
42
- const rawInterpolation : ( string | VariableValue ) [ ] = [ ]
43
- let lastIndex = 0
44
- let matchCount = 0
45
- let canJoin = true
46
42
const variableKeys = sanity ? Object . keys ( variables ) : undefined
43
+ const segments : ( string | VariableValue ) [ ] = [ ]
44
+ let lastIndex = 0
45
+ let foundCount = 0
46
+ let joinable = true
47
47
48
48
let m : RegExpExecArray | null
49
49
while ( ( m = pattern . exec ( string ) ) ) {
50
- const idx = m . index || 0
50
+ const idx = m . index
51
51
const full = m [ 0 ]
52
52
const key = m [ 1 ]
53
53
54
- if ( idx > lastIndex ) rawInterpolation . push ( string . slice ( lastIndex , idx ) )
54
+ if ( idx > lastIndex ) segments . push ( string . slice ( lastIndex , idx ) )
55
55
56
56
if ( sanity && key && ! variableKeys ! . includes ( key ) )
57
57
throw new Error ( `Variable '${ key } ' not found` )
58
58
59
59
const value = variables [ key as unknown as PropertyKey ]
60
- if ( canJoin && typeof value !== "string" && typeof value !== "number" )
61
- canJoin = false
62
- rawInterpolation . push ( value )
60
+ joinable =
61
+ joinable && ( typeof value === "string" || typeof value === "number" )
62
+ segments . push ( value )
63
63
64
64
lastIndex = idx + full . length
65
- matchCount ++
65
+ foundCount ++
66
66
}
67
67
68
- if ( ! matchCount )
68
+ if ( ! foundCount )
69
69
return string as StringInterpolationReturn < VariableValue , OptionRaw >
70
70
71
- if ( lastIndex < string . length ) rawInterpolation . push ( string . slice ( lastIndex ) )
71
+ if ( lastIndex < string . length ) segments . push ( string . slice ( lastIndex ) )
72
72
73
- if ( sanity && matchCount !== variableKeys ! . length )
73
+ if ( sanity && foundCount !== variableKeys ! . length )
74
74
throw new Error ( "Variable count mismatch" )
75
75
76
- if ( canJoin && ! rawOutput )
77
- return rawInterpolation . join ( "" ) as StringInterpolationReturn <
76
+ if ( joinable && ! raw )
77
+ return segments . join ( "" ) as StringInterpolationReturn <
78
78
VariableValue ,
79
79
OptionRaw
80
80
>
81
81
82
- return rawInterpolation as StringInterpolationReturn < VariableValue , OptionRaw >
82
+ return segments as StringInterpolationReturn < VariableValue , OptionRaw >
83
83
}
0 commit comments