-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: ability to do arbitrary string literals (#73)
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
Showing
2 changed files
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}'); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |