Skip to content

Commit

Permalink
feat(strings): add interpolate()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 26, 2020
1 parent f80712f commit a19e409
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/strings/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * from "./center";
export * from "./float";
export * from "./format";
export * from "./hollerith";
export * from "./interpolate";
export * from "./pad-left";
export * from "./pad-right";
export * from "./parse";
Expand Down
20 changes: 20 additions & 0 deletions packages/strings/src/interpolate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const TPL = /\{(\d+)\}/g;

/**
* Takes a string template with embedded `{number}` style terms and any
* number of args. Replaces numbered terms with their respective args
* given.
*
* @example
* ```ts
* interpolate("let {0}: {2} = {1};", "a", 42, "number")
* // "let a: number = 42;"
* ```
*
* @param src
* @param args
*/
export const interpolate = (src: string, ...args: any[]) =>
args.length > 0
? src.replace(TPL, (m) => String(args[parseInt(m[1], 10)]))
: src;

0 comments on commit a19e409

Please sign in to comment.