Skip to content

zirkelc/f-strings

Repository files navigation

f-strings

Tagged template function with embedded if-else conditions and automatic dedentation to write readable strings

Installation

npm install f-strings

Usage

Use If, Else, and EndIf expressions to include conditional content.

import { f, If, Else, EndIf } from 'f-strings';

const history = [
  { role: 'user', content: 'Hello' },
  { role: 'assistant', content: 'Hi there!' },
];

const question = 'What is the capital of France?';

const prompt = f`
  You are a helpful assistant.

  ${If(history.length)}
  Conversation history:
  ${history.map((msg) => `- ${msg.role}: ${msg.content}`)}
  ${Else}
  No conversation history.
  ${EndIf}

  User question:
  ${question}
`;

console.log(message);
You are a helpful assistant.

Conversation history:
- user: Hello
- assistant: Hi there!

User question:
What is the capital of France?

Dedentation

Strips indentation from multi-line strings.

import { f, If, EndIf } from 'f-strings';

const prompt = f`
      Hello
        World!
          How are you?
      I'm good, thank you!
`;

console.log(dedented);
Hello
  World!
    How are you?
I'm good, thank you!

Lazyness

Values will be lazily evaluated, so you can use functions to generate content only when needed.

Tip

Arrays are automatically joined with newlines, so ${messages} is equivalent to ${messages.join('\n')}.

import { f, If, EndIf } from 'f-strings';

const messages = await getMessages(); 

const prompt = f`
  ${If(messages.length)}
    You have ${messages.length} messages:
    ${() => messages.map((msg) => `- ${msg}`)}
  ${Else}
    No messages.
  ${EndIf}
`;

console.log(prompt);
You have 1000 messages:
- Message 1
- Message 2
...
- Message 1000

API

f - Tagged Template Function

const text = f`template ${value} string`

If(condition) - Conditional Block

Starts a conditional block. Includes the following content if the condition is truthy.

const text = f`
  ${If(condition)}
    content when true
  ${EndIf}
`;

Else() - Alternative Block

Starts an alternative block. Includes the following content if the condition is falsy.

Tip

Else can be used without calling it as a function: ${Else} or ${Else()}.

const text = f`
  ${If(condition)}
    content when true
  ${Else}
    content when false
  ${EndIf}
`;

EndIf() - End Conditional

Marks the end of a conditional block. Required for every If.

Tip

EndIf can be used without calling it as a function: ${EndIf} or ${EndIf()}.

License

MIT

About

Template function with embedded if-else conditions and automatic dedentation

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published