Skip to content

Commit

Permalink
feat(string): new template function
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Aug 25, 2021
1 parent aa8d728 commit cedde4b
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/base.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export const assert = (condition: boolean, message: string): asserts condition => {
if (!condition) throw new Error(message)
}
export const toString = Object.prototype.toString
export const toString = (v: any) => Object.prototype.toString.call(v)
export const noop = () => {}
34 changes: 34 additions & 0 deletions src/string.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { template } from './string'

it('template', () => {
expect(
template(
'Hello {0}! My name is {1}.',
'Inès',
'Anthony',
),
).toEqual('Hello Inès! My name is Anthony.')

expect(
template(
'{0} + {1} = {2}{3}',
1,
'1',
{ v: 2 },
[2, 3],
),
).toEqual('1 + 1 = [object Object]2,3')

expect(
template(
'{10}',
),
).toEqual('undefined')

expect(
template(
'Hi',
'',
),
).toEqual('Hi')
})
21 changes: 21 additions & 0 deletions src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,24 @@ export function ensurePrefix(prefix: string, str: string) {
return prefix + str
return str
}

/**
* Dead simple template engine, just like Python's `.format()`
*
* @example
* ```
* const result = template(
* 'Hello {0}! My name is {1}.',
* 'Inès',
* 'Anthony'
* ) // Hello Inès! My name is Anthony.
* ```
*/
export function template(str: string, ...args: any[]): string {
return str.replace(/{(\d+)}/g, (match, key) => {
const index = Number(key)
if (Number.isNaN(index))
return match
return args[index]
})
}

0 comments on commit cedde4b

Please sign in to comment.