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

proxy-extend

v2.0.0

Published

Transparently extend a JS object with additional properties (using ES6 Proxy)

Downloads

256

Readme

proxy-extend

npm GitHub Actions MIT Types

Transparently extend any JS object, using ES6 Proxy.

Motivation

Given some existing JS value, you may want to "annotate" it with some additional information (e.g. for bookkeeping purposes), without actually modifying the original. The simplest way to do so is to create a wrapper around the value:

const someValue = getValue();

const someValueAnnotated = {
    value: someValue,
    status: 'ready',
};

One drawback of using a wrapper object, is that the newly annotated value now has a different interface from the original. That means that any consuming code will need to know about the wrapper and "unwrap" it to do anything with it.

Another possibility is to create a copy of the value, and set the new property on that (e.g. { ...someValue, status: 'ready' }), but this has its own issues once you need to extend something more complex than a plain object (prototypes are not preserved, need to take care to preserve non-enumerable properties, doesn't work with functions or primitives, etc.)

Using ES6 Proxy, we can make the wrapper have the same interface as the original value, allowing us to pass the wrapped value to any consuming code without the consumer needing to know whether it has been proxied or not.

Usage

To import the library:

import extend from 'proxy-extend';

Basic usage:

const user = { name: 'John' }; // Some value to be extended

const userExtended = extend(user, { status: 'ready' });

// The extended value has the same interface as the original
userExtended.name; // 'John'
({ ...userExtended }); // { name: 'John' }

// But we can also access our annotation, if we know the key
userExtended.status; // 'ready'

To make sure that we do not conflict with any existing properties on the original value, it is useful to use a symbol as the key of the annotation:

const user = { name: 'John' };

const meta = Symbol('meta'); // Private symbol

const userExtended = extend(user, { [meta]: 'some metadata' });
userExtended.name; // 'John'
userExtended[meta]; // 'some metadata'

Prototypes are preserved:

class User {
    constructor(name) {
        this.name = name;
    }
}

const meta = Symbol('meta'); // Private symbol

const userExtended = extend(new User('John'), { [meta]: 'some metadata' });
userExtended instanceof User; // true
userExtended[meta]; // 'some metadata'

Can also proxy functions and constructors:

const fn = (a, b) => a + b;
const fnExtended = extend(fn);
fnExtended(2, 3) === 5; // Works

class MyClass {}
const MyClassExtended = extend(MyClass);
new MyClassExtended(); // Works

API

import extend from 'proxy-extend';
  • extend(value, extension = {})

    Returns a proxy representing the given value, extended with the properties of the extension. If value is already a proxy (created using extend), it will flatten the result to prevent nested proxies.

  • extend.is(value)

    Check if the given value has been extended.

  • extend.unwrap(extendedValue)

    Can be used to retrieve the original value and extension:

    extend.unwrap(proxy).value; // The original value
    extend.unwrap(proxy).extension; // The extension object

Limitations

Primitives

Due to the nature of Proxy, we can only use an object as target value. This library supports any JS object, including plain objects, arrays, functions, and class constructors. We also support a few kinds of primitives by emulating them using objects:

  • null (using an empty object, with null prototype)
  • Strings (using boxed String)
  • Numbers (using boxed Number)

Reference equality

You cannot use == to check equality, the proxy is a different reference:

const value = { x: 42 };
const proxy = extend(value);

value !== proxy; // Reference equality does not hold

Instead, you can use extend.unwrap to access the original value:

extend.unwrap(proxy).value === value;

// Or, you may want to add a convenience method:
const value = { x: 42 };
const proxy = extend(value, {
    is(other) { return extend.unwrap(this).value === other; },
});
proxy.is(value) === true;

For primitives, you can use .valueOf(), or cast using a constructor:

const proxyString = extend('foo');
proxyString !== 'foo'; // Won't work

proxyString.valueOf() === 'foo'; // Get primitive value
String(proxyString) === 'foo'; // Or, cast to string using `String` constructor

Similar libraries