npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

interpolatable

v1.3.2

Published

Fast memoization for interpolatable entities

Downloads

382

Readme

interpolatable

npm version Coverage Status Build Status Bundle Phobia

A super tiny ( < 600 bytes minzipped) package that allows you to quickly (⚡) interpolate any values into any other value!

Installation

npm install interpolatable
## or
yarn add interpolatable

Or directly via the browser:

<script src="https://cdn.jsdelivr.net/npm/interpolatable"></script>
<script>
  const descriptor = 'Hello {{user}}!';
  const interpolate = interpolatable(descriptor);
  const interpolated = interpolate({ user: 'Joe' });
  // Hello Joe!
</script>

Usage

import interpolatable from 'interpolatable';

const interpolate = interpolatable({
  weather: {
    params: {
      query: '{{city}}',
      appId: '{{apiKey}}',
      units: '{{units}}',
    },
    path: 'main.temp',
    is: {
      type: 'number',
      minimum: '{{hotTemp}}',
    },
  },
});

const result = interpolate({
  city: 'Halifax',
  apiKey: 'XXX',
  units: 'metric',
  minimum: 20,
});

/*
{
  weather: {
    params: {
      query: 'Halifax',
      appId: 'XXX',
      units: 'metric',
    },
    path: 'main.temp',
    is: {
      type: 'number',
      minimum: 20,
    },
  },
}
*/

What in the heck is this good for?

Two things:

  1. Interpolating complex objects
  2. Doing 1 fast ⚡ (while maintaining referential integrity)

Referential Integrity

The "dependencies" of some nested structure to be interpolated are, in the below descriptor, defined by strings like: {{city}}

const descriptor = {
  weather: {
    params: {
      query: '{{city}}',
      appId: '{{apiKey}}',
      units: '{{units}}',
    },
    path: 'main.temp',
    is: {
      type: 'number',
      minimum: '{{hotTemp}}',
    },
  },
};

Rather than parse the entire structure every time it needs to be interpolated, which is expensive, we check at each node to see if the dependencies of that node (if there are any) have changed since the last run. If they haven't, then we return the last object and we can skip the expensive parsing operation.

The dependencies of the root node are: city, apiKey, units, and hotTemp. But if only hotTemp changes between interpolations, we don't need to re-evaluate weather.params because it's dependencies - city, apiKey, and units haven't changed. So:

const interpolate = interpolatable(descriptor);

const first = interpolate({
  city: 'Halifax',
  apiKey: 'XXX',
  units: 'metric',
  minimum: 20,
});

const second = interpolate({
  city: 'Halifax',
  apiKey: 'XXX',
  units: 'metric',
  minimum: 25,
});

console.log(first === second); // false
console.log(first.weather.params === second.weather.params); // same object! dependencies didn't change between runs

API

function interpolatable<T = string | Record<string, unknown> | unknown[]>(
  subject: T,
  options?: Options<R>,
): <R>(context: R) => T;

type Options<R> = {
  pattern?: RegExp | null;
  resolver?: Resolver<R>;
  skip?: RegExp;
};

type Resolver<R = unknown> = (context: R, subject: string) => unknown;

Pass a subject (any interpolatable string, object, or array) to the default export, and optionally options and it returns an interpolation function which accepts a data source to interpolate from.

Options

pattern: RegExp = /\{\{\s*(.+?)\s*\}\}/g

The default interpolation pattern is a RegExp that matches a string between {{ }} - some_string in {{some_string}}. You can pass in a custom pattern if you like:

const interpolate = interpolatable(
  {
    foo: '<%= bar %> qux',
  },
  {
    pattern: /<%=\s*(.+?)\s*%>/g,
  },
);

const result = interpolate({ bar: 'baz' });
/*
 { foo: 'baz qux' }
*/

Note: pattern can also be null. If pattern is passed as null, interpolatable will return a function that always returns your unaltered subject.

resolver: (context: R, subject: string) => unknown

A resolver is a function that accepts a context and interpolated string and synchronously returns any value, it doesn't have to be a primitive.

The default resolver returns the value from the context indexed by the string:

const DEFAULT_RESOLVER = (c, k) => c[k];

Other good resolvers are lodash's get or property-expr, or jsonpointer.

import expr from 'property-expr';

const interpolate = interpolatable(
  {
    foo: '{{bar.baz}}',
  },
  {
    resolver: (context, subject) => expr.getter(subject)(context),
  },
);

const result = interpolate({
  bar: {
    baz: 'qux',
  },
});

/*
 { foo: 'qux' }
*/

skip: RegExp

Sometimes we want to interpolate a very large deeply nested object. Traversing the entire object is often unnecessary and can be very expensive. This is where skip comes in. When skip is defined, all paths, while traversing the subject, will be tested against it. If the path matches the skip RegExp, anything beneath it will not be traversed.

const interpolate = interpolatable(
  {
    foo: '{{someString}}',
    bar: {
      some: {
        deeply: {
          nested: {
            expensive_to_traverse: {
              object: []
            }
          }
        }
      }
    }
  },
  {
    skip: /bar/
  }
)

delimieter: string = '.'

The delimiter is the thing that joins path segments and defaults to a .. Useful to configure if you're skip RegExp is restrictive.

import { get } from 'json-pointer';

const interpolate = interpolatable(
  {
    foo: '{{/bar/baz}}',
  },
  {
    resolver: get,
  },
);

const result = interpolate({
  bar: {
    baz: 'qux',
  },
});

/*
 { foo: 'qux' }
*/

Other Cool Stuff

Check out json-schema-rules-engine or json-modifiable for a more practical application.

License

MIT

Contributing

PRs welcome!