Skip to content

Instantly share code, notes, and snippets.

@fogfish
Created August 14, 2019 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fogfish/f5aacda854a52a8dbfd701b70fc8c278 to your computer and use it in GitHub Desktop.
Save fogfish/f5aacda854a52a8dbfd701b70fc8c278 to your computer and use it in GitHub Desktop.
class Text {
static f(str: TemplateStringsArray, ...args: Array<any>) {
return <A>(...props: Array<A>): string => {
const parsed = args.map((x, index) => (typeof x === 'function' ? x(props[index]) : x))
if (parsed.some(x => x === undefined)) {
return ''
}
return str.reduce((acc, substr, index) => acc + this.text(parsed[index - 1]) + substr)
}
}
static text(x: any): string {
if (Array.isArray(x)) {
return `(${x.map(this.text)})`
}
return this.stringify(x)
}
static stringify(x: any): string {
return String(x)
}
}
class Json extends Text {
static stringify(x: any): string {
return JSON.stringify(x)
}
}
const text = Text.f`foo ${x => x}`
const json = Json.f`foo ${x => x}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment