Default composer

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

README

Default composer logo

Default composer


_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][badge-prwelcome]][prwelcome]
All Contributors


[badge-prwelcome]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square

[prwelcome]: http://makeapullrequest.com

"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:

  - [defaultComposer](#defaultcomposer)
  - [setConfig](#setconfig)
    - [isDefaultableValue](#isdefaultablevalue)
    - [mergeArrays](#mergearrays)

Installation


You can install "default-composer" using npm:

  1. ```bh
  2. npm install default-composer
  3. ```

or with yarn:

  1. ```bh
  2. yarn add default-composer
  3. ```

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:

  1. ```js
  2. import { defaultComposer } from "default-composer";

  3. const defaults = {
  4.   name: "Aral 😊",
  5.   surname: "",
  6.   isDeveloper: true,
  7.   isDesigner: false,
  8.   age: 33,
  9.   address: {
  10.     street: "123 Main St",
  11.     city: "Anytown",
  12.     state: "CA",
  13.   },
  14.   emails: ["contact@aralroca.com"],
  15.   hobbies: ["programming"],
  16. };

  17. const originalObject = {
  18.   name: "Aral",
  19.   emails: [],
  20.   phone: "555555555",
  21.   age: null,
  22.   address: {
  23.     zip: "54321",
  24.   },
  25.   hobbies: ["parkour", "computer science", "books", "nature"],
  26. };

  27. const result = defaultComposer(defaults, originalObject);

  28. console.log(result);
  29. ```

This will output:

  1. ```js
  2. {
  3.   name: 'Aral',
  4.   surname: '',
  5.   isDeveloper: true,
  6.   isDesigner: false,
  7.   emails: ['contact@aralroca.com'],
  8.   phone: '555555555',
  9.   age: 33,
  10.   address: {
  11.     street: '123 Main St',
  12.     city: 'Anytown',
  13.     state: 'CA',
  14.     zip: '54321'
  15.   },
  16.   hobbies: ['parkour', 'computer science', 'books', 'nature'],
  17. }
  18. ```

API


defaultComposer


  1. ```js
  2. defaultComposer(defaultsPriorityN, [..., defaultsPriority2, defaultsPriority1, objectWithData])
  3. ```

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:

  1. ```js
  2. import { defaultComposer } from "default-composer";

  3. const defaultsPriority1 = {
  4.   name: "Aral 😊",
  5.   hobbies: ["reading"],
  6. };

  7. const defaultsPriority2 = {
  8.   name: "Aral 🤔",
  9.   age: 33,
  10.   address: {
  11.     street: "123 Main St",
  12.     city: "Anytown",
  13.     state: "CA",
  14.     zip: "12345",
  15.   },
  16.   hobbies: ["reading", "hiking"],
  17. };

  18. const object = {
  19.   address: {
  20.     street: "",
  21.     city: "Anothercity",
  22.     state: "NY",
  23.     zip: "",
  24.   },
  25.   hobbies: ["running"],
  26. };

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

  28. console.log(result);
  29. ```

This will output:

  1. ```js
  2. {
  3.   name: 'Aral 😊',
  4.   age: 33,
  5.   address: {
  6.     street: '123 Main St',
  7.     city: 'Anothercity',
  8.     state: 'NY',
  9.     zip: '12345'
  10.   },
  11.   hobbies: ['running']
  12. }
  13. ```

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.

  1. ```ts
  2. type IsDefaultableValueParams = ({
  3.   key,
  4.   value,
  5.   defaultableValue,
  6. }: {
  7.   key: string;
  8.   value: unknown;
  9.   defaultableValue: boolean; // In case you want to re-use the default behavior
  10. }) => boolean;
  11. ```

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:

  1. ```ts
  2. import { defaultComposer, setConfig } from "default-composer";

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

  6. setConfig({ isDefaultableValue: isNullOrWhitespace });

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

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

  1. ```ts
  2. import { defaultComposer, setConfig } from "default-composer";

  3. setConfig({
  4.   isDefaultableValue({ key, value, defaultableValue }) {
  5.     return (
  6.       defaultableValue || (typeof value === "string" && value.trim() === "")
  7.     );
  8.   },
  9. });

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

mergeArrays


Example to merge arrays:

  1. ```ts
  2. const defaults = {
  3.   hobbies: ["reading"],
  4. };

  5. const object = {
  6.   hobbies: ["running"],
  7. };
  8. setConfig({ mergeArrays: true});

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

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:

  1. ```ts
  2. type Addres = {
  3.   street: string;
  4.   city: string;
  5.   state: string;
  6.   zip: string;
  7. };

  8. type User = {
  9.   name: string;
  10.   age: number;
  11.   address: Address;
  12.   hobbies: string[];
  13. };

  14. const defaults = {
  15.   name: "Aral 😊",
  16.   hobbies: ["reading"],
  17. };

  18. const object = {
  19.   age: 33,
  20.   address: {
  21.     street: "",
  22.     city: "Anothercity",
  23.     state: "NY",
  24.     zip: "",
  25.   },
  26.   hobbies: [],
  27. };

  28. defaultComposer<User>(defaults, object);
  29. ```

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.

<img src="https://img.shields.io/twitter/follow/aralroca?style=social&logo=twitter"
alt="follow on Twitter">

Contributors ✨


Thanks goes to these wonderful people (emoji key):

Aral Roca Gomez
Aral Roca Gomez

💻 🚧
Robin Pokorny
Robin Pokorny

💻
Muslim Idris
Muslim Idris

💻
namhtpyn
namhtpyn

🚇



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