Skip to content

Commit

Permalink
fix: enhance TemplateStringArray detection
Browse files Browse the repository at this point in the history
  • Loading branch information
antongolub committed Sep 19, 2024
1 parent 3c51dee commit 10dc031
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
9 changes: 8 additions & 1 deletion src/main/ts/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,14 @@ export const makeDeferred = <T = any, E = any>(): { promise: Promise<T>, resolve

export const isPromiseLike = (value: any): boolean => typeof value?.then === 'function'

export const isStringLiteral = (pieces: any) => pieces?.every?.((p: any) => typeof p === 'string')
export const isStringLiteral = (
pieces: any,
...rest: any[]
): pieces is TemplateStringsArray =>
pieces?.length > 0 &&
pieces.raw?.length === pieces.length &&
Object.isFrozen(pieces) &&
rest.length + 1 === pieces.length

export const assign = <T, E>(target: T, ...extras: E[]): T =>
Object.defineProperties(target, extras.reduce<Record<string, any>>((m: any, extra) =>
Expand Down
2 changes: 1 addition & 1 deletion src/main/ts/x.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export const $: TShell = function(this: any, pieces?: any, ...args: any): any {

if (pieces === undefined) return applyMixins($, preset)

if (isStringLiteral(pieces)) return ignite(preset, pieces, ...args)
if (isStringLiteral(pieces, ...args)) return ignite(preset, pieces, ...args)

return (...args: any) => $.apply(self ? assign(self, pieces) : pieces, args)
}
Expand Down
15 changes: 13 additions & 2 deletions src/test/ts/util.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
import * as assert from 'node:assert'
import { describe, it } from 'node:test'
import { assign } from '../../main/ts/util.js'
import {describe, it, test} from 'node:test'
import { assign, isStringLiteral } from '../../main/ts/util.js'

describe('util', () => {
it('assign()', () => {
assert.deepEqual(assign({a: 1}, {b: 2}), {a: 1, b: 2})
assert.deepEqual(assign({a: 1}, {a: undefined}), {a: 1})
})

test('isStringLiteral()', () => {
const bar = 'baz'
assert.ok(isStringLiteral``)
assert.ok(isStringLiteral`foo`)
assert.ok(isStringLiteral`foo ${bar}`)

assert.ok(!isStringLiteral(''))
assert.ok(!isStringLiteral('foo'))
assert.ok(!isStringLiteral(['foo']))
})
})

0 comments on commit 10dc031

Please sign in to comment.