Skip to content

utils replaceVars()

Eugene Lazutkin edited this page Apr 3, 2026 · 3 revisions

Template literal function that replaces variables with their bound values.

Introduction

Creates a template string function that substitutes Variable instances and variable names with their bound values from an Env. Useful for debugging or generating strings from unified variables.

import replaceVars from 'deep6/utils/replaceVars.js';
import {variable} from 'deep6/env.js';
import unify from 'deep6/unify.js';

const x = variable('x');
const y = variable('y');
const env = unify({x: 42, y: 'world'}, {x, y});

const template = replaceVars(env);
const result = template`The answer is ${x} and ${y}!`;
// result === "The answer is 42 and world!"

API

replaceVars(env)

Arguments:

  • env — a required Env containing variable bindings.

Returns a template literal function.

Template Function

The returned function has the signature:

(strings: TemplateStringsArray, ...vars) => string
  • strings — the template string parts (provided by JS engine).
  • vars — interpolated values which can be:
    • Variable instances — replaced with variable.get(env).
    • string, number, symbol — treated as variable names, replaced with env.values[name].
    • Any other value — converted to string directly.

Examples

import replaceVars from 'deep6/utils/replaceVars.js';
import {variable} from 'deep6/env.js';
import unify from 'deep6/unify.js';

const x = variable('x');
const y = variable('y');
const env = unify({x: 42, y: 'world'}, {x, y});
const t = replaceVars(env);

// Using Variable instances
t`Value: ${x}`; // "Value: 42"

// Using variable names as strings
t`Value: ${'x'}`; // "Value: 42"

// Mixed usage
t`${x} + ${y} = ${42 + 42}`; // "42 + world = 84"

// Practical debugging example
const result = unify(pattern, data);
console.log(t`Matched: x=${x}, y=${y}`);

Clone this wiki locally