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

default-composer

v0.6.0

Published

A JavaScript library that allows you to set default values for nested objects

Downloads

7,100

Readme

A tiny (~500B) JavaScript library that allows you to set default values for nested objects

npm version gzip size CI Status Maintenance Status Weekly downloads PRs Welcome All Contributors

"default-composer" is a JavaScript library that allows you to set default values for nested objects. The library replaces empty strings/arrays/objects, null, or undefined values in an existing object with the defined default values, which helps simplify programming logic and reduce the amount of code needed to set default values.

Content:

Installation

You can install "default-composer" using npm:

npm install default-composer

or with yarn:

yarn add default-composer

Usage

To use "default-composer", simply import the library and call the defaultComposer() function with the default values object and the original object that you want to set default values for. For example:

import { defaultComposer } from "default-composer";

const defaults = {
  name: "Aral 😊",
  surname: "",
  isDeveloper: true,
  isDesigner: false,
  age: 33,
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA",
  },
  emails: ["[email protected]"],
  hobbies: ["programming"],
};

const originalObject = {
  name: "Aral",
  emails: [],
  phone: "555555555",
  age: null,
  address: {
    zip: "54321",
  },
  hobbies: ["parkour", "computer science", "books", "nature"],
};

const result = defaultComposer(defaults, originalObject);

console.log(result);

This will output:

{
  name: 'Aral',
  surname: '',
  isDeveloper: true,
  isDesigner: false,
  emails: ['[email protected]'],
  phone: '555555555',
  age: 33,
  address: {
    street: '123 Main St',
    city: 'Anytown',
    state: 'CA',
    zip: '54321'
  },
  hobbies: ['parkour', 'computer science', 'books', 'nature'],
}

API

defaultComposer

defaultComposer(defaultsPriorityN, [..., defaultsPriority2, defaultsPriority1, objectWithData])

This function takes one or more objects as arguments and returns a new object with default values applied. The first argument should be an object containing the default values to apply. Subsequent arguments should be the objects to apply the default values to.

If a property in a given object is either empty, null, or undefined, and the corresponding property in the defaults object is not empty, null, or undefined, the default value will be used.

Example:

import { defaultComposer } from "default-composer";

const defaultsPriority1 = {
  name: "Aral 😊",
  hobbies: ["reading"],
};

const defaultsPriority2 = {
  name: "Aral 🤔",
  age: 33,
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA",
    zip: "12345",
  },
  hobbies: ["reading", "hiking"],
};

const object = {
  address: {
    street: "",
    city: "Anothercity",
    state: "NY",
    zip: "",
  },
  hobbies: ["running"],
};

const result = defaultComposer(defaultsPriority2, defaultsPriority1, object);

console.log(result);

This will output:

{
  name: 'Aral 😊',
  age: 33,
  address: {
    street: '123 Main St',
    city: 'Anothercity',
    state: 'NY',
    zip: '12345'
  },
  hobbies: ['running']
}

setConfig

setConfig is a function that allows you to set configuration options for defaultComposer.

This is the available configuration:

  • isDefaultableValue, is a function that determines whether a value should be considered defaultable or not.
  • mergeArrays, is a boolean to define if you want to merge arrays (true) or not (false), when is set to false is just replacing to the default value when the original array is empty. By default is false.

isDefaultableValue

You can use setConfig to provide your own implementation of isDefaultableValue if you need to customize this behavior.

type IsDefaultableValueParams = ({
  key,
  value,
  defaultableValue,
}: {
  key: string;
  value: unknown;
  defaultableValue: boolean; // In case you want to re-use the default behavior
}) => boolean;

The defaultableValue boolean is the result of the default behavior of isDefaultableValue. By default, is detected as defaultableValue when is null, undefined, an empty string, an empty array, or an empty object.

Here is an example of how you can use setConfig:

import { defaultComposer, setConfig } from "default-composer";

const isNullOrWhitespace = ({ key, value }) => {
  return value === null || (typeof value === "string" && value.trim() === "");
};

setConfig({ isDefaultableValue: isNullOrWhitespace });

const defaults = { example: "replaced", anotherExample: "also replaced" };
const originalObject = { example: "   ", anotherExample: null };
const result = defaultComposer<any>(defaults, originalObject);
console.log(result); // { example: 'replaced', anotherExample: 'also replaced' }

Here is another example of how you can use setConfig reusing the defaultableValue:

import { defaultComposer, setConfig } from "default-composer";

setConfig({
  isDefaultableValue({ key, value, defaultableValue }) {
    return (
      defaultableValue || (typeof value === "string" && value.trim() === "")
    );
  },
});

const defaults = { example: "replaced", anotherExample: "also replaced" };
const originalObject = { example: "   ", anotherExample: null };
const result = defaultComposer<any>(defaults, originalObject);
console.log(result); // { example: 'replaced', anotherExample: 'also replaced' }

mergeArrays

Example to merge arrays:

const defaults = {
  hobbies: ["reading"],
};

const object = {
  hobbies: ["running"],
};
setConfig({ mergeArrays: true});

defaultComposer<any>(defaults, object)) // { hobbies: ["reading", "running"]}

TypeScript

In order to use in TypeScript you can pass a generic with the expected output, and all the expected input by default should be partials of this generic.

Example:

type Addres = {
  street: string;
  city: string;
  state: string;
  zip: string;
};

type User = {
  name: string;
  age: number;
  address: Address;
  hobbies: string[];
};

const defaults = {
  name: "Aral 😊",
  hobbies: ["reading"],
};

const object = {
  age: 33,
  address: {
    street: "",
    city: "Anothercity",
    state: "NY",
    zip: "",
  },
  hobbies: [],
};

defaultComposer<User>(defaults, object);

Contributing

Contributions to "default-composer" are welcome! If you find a bug or want to suggest a new feature, please open an issue on the GitHub repository. If you want to contribute code, please fork the repository and submit a pull request with your changes.

License

"default-composer" is licensed under the MIT license. See LICENSE for more information.

Credits

"default-composer" was created by Aral Roca.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!