Skip to content

Commit

Permalink
feat(strings): add interpolateKeys()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 4, 2021
1 parent fb4470d commit bd78d1d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/strings/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"functional",
"hex",
"higher-order",
"interpolation",
"number",
"padding",
"percent",
Expand Down
29 changes: 28 additions & 1 deletion packages/strings/src/interpolate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import type { IObjectOf, NumOrString } from "@thi.ng/api";
import { illegalArgs } from "@thi.ng/errors";

const TPL = /\{(\d+)\}/g;
const TPL_K = /\{([a-z0-9_.-]+)\}/gi;

/**
* Takes a string template with embedded `{number}` style terms and any
Expand All @@ -16,5 +20,28 @@ const TPL = /\{(\d+)\}/g;
*/
export const interpolate = (src: string, ...args: any[]) =>
args.length > 0
? src.replace(TPL, (m) => String(args[parseInt(m[1], 10)]))
? src.replace(TPL, (_, id) => String(args[parseInt(id, 10)]))
: src;

/**
* Similar to {@link interpolate}, but uses alphanumeric placeholders in the
* template string and an object of values for the stated keys.
*
* @example
* ```ts
* interpolateKeys(
* "let {id}: {type} = {val};",
* { id: "a", type: "number", val: 42 }
* )
* // "let a: number = 42;"
* ```
*
* @param src
* @param keys
*/
export const interpolateKeys = (src: string, keys: IObjectOf<NumOrString>) =>
src.replace(TPL_K, (_, id) =>
keys[id] != undefined
? String(keys[id])
: illegalArgs(`missing key: ${id}`)
);

0 comments on commit bd78d1d

Please sign in to comment.