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

@status/defaults

v1.5.0

Published

Transparently provide default values to objects

Downloads

8

Readme

Defaults

npm (scoped) GitHub GitHub Workflow Status (with branch) npm bundle size (scoped) npm bundle size (scoped)

Transparently supply default values for JavaScript Objects.


Install

npm install @status/defaults

or

yarn add @status/defaults


Usage

Defaults exposes a function, wrapDefaults, that receives your object and any options;

import { wrapDefaults } from '@status/defaults';

const wrapped = wrapDefaults({
  wrap: myObject,
  /** options explained below */
});

Defaults default is undefined, which makes it rather useless, so supplying your own default is a good idea.

Additionally, it accepts a function, setCriteria, that can be used to determine if a default value should be used instead of the value being set. Returning true, or any truthy value, will result in your default value being set.

import { wrapDefaults } from '@status/defaults';

const wrapped = wrapDefaults({
  wrap: myObject,
  defaultValue: 0,
  setCriteria: (value: number, _property: string, _myObject: T) => value < 0,
});

wrapped.belowZero = -35;

expect(wrapped.belowZero).to.equal(0);

Be aware that while defaults are supplied for undefined values they are not set. This behavior may be modified.

import { wrapDefaults } from '@status/defaults';

const wrapped = wrapDefaults({
  defaultValue: 0,
  setUndefined: true,
});

expect(wrapped.notThere).to.equal(0);

Using complex content as a default is possible, but only shallow copies are made.

const complex = wrapDefaults({
  defaultValue: [[2.345, 43.53]],
  setUndefined: true,
});

expect(complex.point1).to.not.equal(complex.point2);
expect(complex.point1[0]).to.equal(complex.point2[0]);

This can be changed by passing shallowCopy as false. ShallowCopy has no effect when using primitive values.

const complex = wrapDefaults({
  defaultValue: [[2.345, 43.53]],
  setUndefined: true,
  shallowCopy: false,
});

expect(complex.point1).to.not.equal(complex.point2);
expect(complex.point1[0]).to.not.equal(complex.point2[0]);

You can also use a function as a default value. If execute is true the function will be executed and the result returned.

const wrapped = wrapDefaults({
  defaultValue: () => 2 + 2,
  setUndefined: true,
  execute: true,
});

expect(wrapped.four).to.equal(4);

The function will receive the property being accessed as its first argument.

const wrapped = wrapDefaults({
  defaultValue: (prop) => prop,
  setUndefined: true,
  execute: true,
});

expect(wrapped.four).to.equal('four');

If you want to use a function as a default value but not execute it, set execute to false.

const wrapped = wrapDefaults({
  defaultValue: () => 2 + 2,
  setUndefined: true,
  execute: false,
});

expect(wrapped.four).to.be.a('function');

Using wrapDefaults helper will add a type for unwrapDefaults method which, when invoked, returns the original unwrapped object.

import { wrapDefaults } from '@status/defaults';

class Person {}

const person = new Person();
const defaults = wrapDefaults({ wrap: person });
const unwrapped = defaults.unwrapDefaults();

expect(person).to.not.equal(defaults);
expect(person).to.equal(unwrapped);

Defaults can also wrap arrays.

import { wrapDefaults } from '@status/defaults';

const array = wrapDefaults({
  wrap: [] as number[],
  defaultValue: 7,
  setCriteria: (v) => v < 7,
  setUndefined: true,
});

expect(array[0]).to.equal(7);

array.push(1);

expect(array[1]).to.equal(7);

Defaults defaults

All options have default values.

| Option | Default Value | Description | | :----------: | :-----------: | ---------------------------------------------------------------------------------------------------------------------- | | wrap | {} | The object to wrap | | shallowCopy | true | Only create shallow copies of defaultValue objects | | setUndefined | false | Set undefined values with defaultValue | | defaultValue | undefined | The value to return if resolved value is undefined | | setCriteria | () => false | Function that can override value to be set with the defaultValue | | execute | false | If true and defaultValue is a function it will be executed and the result returned. Receives property being accessed | | noCopy | false | Indicates if non-primitive default values should be returned as-is | | reuseMapKey | true | If true and default value is a Map the key will be reused, otherwise shallowCopy rules apply | | runAfterSet | () => {} | Function to run after a default value is set. setUndefined must be true |


Override

You may override your defined criteria should you really need to set a value that would fail.

const aboveZero = wrapDefaults({
  defaultValue: 0,
  setCriteria: (v) => v < 0,
});

aboveZero.notAnymore = { ignoreDefaultCriteria: true, value: -345 };

console.log(aboveZero);
// => { notAnymore: -345 }

Info

Determining if a property exists on an object is unaffected when using Defaults, even when using setUndefined.

const wrapped = wrapDefaults({ defaultValue: [], setUndefined: true });
const prop = 'prop';

expect(prop in wrapped).to.be.false;

Examples

import { wrapDefaults } from '@status/defaults';

const charCount = wrapDefaults({
  setCriteria: (v) => v < 0,
  setUndefined: true,
  defaultValue: 0,
});

const sentence = 'something wicked this way comes';

// do this (using Defaults)
for (const char of sentence) {
  charCount[char]++;
}

// instead of this (without Defaults)
for (const char of sentence) {
  if (!(char in charCount)) {
    charCount[char] = 0;
  }

  charCount[char]++;
}

Ever done something like this?

const myObj = { prop1: [] };


(myObj.propMaybeExists || []).forEach(...);

Use defaults instead.

const myObj = wrapDefaults({ defaultValue: [] });

myObj.ifNotExistsWillStillHaveArray.forEach(...);