Skip to content

Commit

Permalink
feat: ability to do arbitrary string literals (#73)
Browse files Browse the repository at this point in the history
Used for when using values from the configuration file for creating values in the editor.

For example, being able to provide a preview url with a param for the workspace: `https://project-${workspace}.domain.com/`
  • Loading branch information
Zoramite committed Jul 7, 2021
1 parent 2bf1c3a commit f6a1981
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/ts/utility/stringLiteral.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {interpolate} from './stringLiteral';
import test from 'ava';

test('correctly interpolates text with params', t => {
t.is(interpolate({foo: 'bar'}, 'test ${foo}'), 'test bar');
t.is(interpolate({foo: 'bar'}, 'test ${foo} ${foo.length}'), 'test bar 3');
});

test('error with interpolates with unknown param', t => {
t.throws(() => {
interpolate({foo: 'bar'}, 'test ${foo} ${bar}');
});
});
21 changes: 21 additions & 0 deletions src/ts/utility/stringLiteral.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Used with normal input strings to provide values to interpolate using a
* set of params.
*
* ```js
* const template = 'Example text: ${text}';
* const result = interpolate({
* text: 'Foo bar'
* }, template);
* // Example text: Foo bar
* ```
*
* @param params Params to be used in the interpolate.
* @param value Normal string value to interpolate.
* @returns String literal interpolated string.
*/
export function interpolate(params: Record<string, any>, value: string) {
const names = Object.keys(params);
const vals = Object.values(params);
return new Function(...names, `return \`${value}\`;`)(...vals);
}

0 comments on commit f6a1981

Please sign in to comment.