Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat(namedTemplate): new function
  • Loading branch information
jd-solanki committed Jun 28, 2023
commit ebaa285a8b047f3c15eeedb24ce92e1a2b23c4f8
42 changes: 41 additions & 1 deletion src/string.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, it } from 'vitest'
import { capitalize, ensurePrefix, ensureSuffix, slash, template } from './string'
import { capitalize, ensurePrefix, ensureSuffix, namedTemplate, slash, template } from './string'

it('template', () => {
expect(
Expand Down Expand Up @@ -34,6 +34,46 @@ it('template', () => {
).toEqual('Hi')
})

it('namedTemplate', () => {
expect(
namedTemplate(
'{greet}! My name is {name}.',
{ greet: 'Hello', name: 'Anthony' },
),
).toEqual('Hello! My name is Anthony.')

expect(
namedTemplate(
'{a} + {b} = {result}',
{ a: 1, b: 2, result: 3 }
),
).toEqual('1 + 2 = 3')

// Without fallback return the variable name
expect(
namedTemplate(
'{10}',
{},
),
).toEqual('10')

expect(
namedTemplate(
'{10}',
{},
'unknown'
),
).toEqual('unknown')

expect(
namedTemplate(
'{10}',
{},
''
),
).toEqual('')
})

it('slash', () => {
expect(slash('\\123')).toEqual('/123')
expect(slash('\\\\')).toEqual('//')
Expand Down
19 changes: 19 additions & 0 deletions src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,25 @@ export function template(str: string, ...args: any[]): string {
})
}

/**
* Dead simple named template engine, just like Python's
*
* @category String
* @example
* ```
* const result = template(
* '{greet}! My name is {name}.',
* { greet: 'Hello', name: 'Anthony' }
* ) // Hello! My name is Anthony.
* ```
*/
export function namedTemplate(str: string, vars: Record<string, any>, fallback: null | undefined | string = null): string {
return str.replace(
/{(\w+)}/g,
(_, variable) => vars[variable] || (fallback ?? variable),
)
}

// port from nanoid
// https://github.com/ai/nanoid
const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
Expand Down