• Stars
    star
    462
  • Rank 94,832 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 1 year ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A tiny (~500B) JavaScript library that allows you to set default values for nested objects
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 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.

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!

More Repositories

1

next-translate

Next.js plugin + i18n API for Next.js 🌍 - Load page translations and use them in an easy way!
JavaScript
2,614
star
2

diff-dom-streaming

HTML Streaming Over the Wire! πŸ₯³ Diff DOM algorithm with streaming to make only the necessary modifications, insertions and deletions between a DOM node and an HTML stream reader.
TypeScript
118
star
3

prerender-macro

Bun plugin to prerender JSX components using a kind of macro
TypeScript
86
star
4

etiketai

Etiketai is an online tool designed to label images, useful for training AI models
JavaScript
76
star
5

MNIST_React_TensorFlowJS

This repo is a POC about using a trained Keras model with MNIST database with TensorFlow.js and React.js!
JavaScript
65
star
6

posenet-d3

D3 graph controlled with the camara (TensorFlow.JS with posenet)
JavaScript
51
star
7

react-text-toxicity

Detect text toxicity in a simple way, using React. Based in a Keras model, loaded with Tensorflow.js.
JavaScript
44
star
8

aralroca

My GitHub profile
Rust
39
star
9

next-translate-plugin

Next-translate plugin for i18n in Next.js 🌍 - Load page translations and use them in an easy way!
JavaScript
30
star
10

chat-with-deno-and-preact

Chat app with Deno + Preact
TypeScript
27
star
11

fishFollow-posenet-tfjs

POC with posenet to move a fish with the movement of your head (using the webcam)
JavaScript
27
star
12

helloworld-angular-with-golang

Angular 4 served by Golang server
TypeScript
27
star
13

next-load

Load & consume data in an easy way in Next.js +13 app dir
TypeScript
24
star
14

parse-html-stream

During the HTML streaming, capture the DOM Nodes to work with them
TypeScript
21
star
15

running-stabilizer

Stabilizing any YouTube video meanwhile you are running on a jogging machine.
JavaScript
18
star
16

aralroca.com

My personal webpage / blog
TypeScript
12
star
17

cat-dog-detection-tfjs

Cat/Dog detection model in Tensorflow.js
JavaScript
10
star
18

webgl-gears

Dynamic gears implemented with WebGL
JavaScript
9
star
19

js-paging

Paging badges generator
TypeScript
7
star
20

helloworld-wasm-rust

Hello world code with WebAssembly and Rust
HTML
6
star
21

media_recorder

sound recorder in Angular2 using MediaRecorder API
TypeScript
6
star
22

speech_recognition

Speech Recognition with Angular2
TypeScript
5
star
23

web-to-electron-app

Transform a web to an Electron app
JavaScript
4
star
24

example-brisa-view-transition

Example of View Transitions in Brisa
TypeScript
2
star
25

nature_in_code

Nature in Code; notes and exercises
JavaScript
2
star
26

wyhash

wyhash available for Bun, Node and Deno
TypeScript
2
star
27

vidBits

Project for TDD course from CodeAcademy
JavaScript
1
star
28

bulb-voice-control

Change color of bulb (BLE) saying the color (with voice)
TypeScript
1
star
29

associacio_catalana_de_parkour

AssociaciΓ³ Catalana de Parkour
JavaScript
1
star
30

check-domain-names

Check a list of domain names if are available
JavaScript
1
star
31

astronomical-clock

Astronomical clock app (with ionic)
TypeScript
1
star
32

HTMLPortalElement-react-example

Using HTMLPortalElement with React. Just a POC.
JavaScript
1
star
33

LinearRegressorTFjsReact

Proof of concept of a Linear Regressor model with TensorFlow.js and React.
JavaScript
1
star
34

ourparkbcn

Parkour classes in Barcelona
TypeScript
1
star
35

ng-bulb

Controlling a Magic Blue Bulb with Ionic 2 and BLE
TypeScript
1
star
36

gather

TDD CodeAcademy project
JavaScript
1
star
37

smartmirror

Smart Mirror with Angular2 (Used Angular-CLI) and Electron
TypeScript
1
star
38

image-processing-webgl

Examples of image processing using WebGL
JavaScript
1
star
39

counter-wc

An example of Web Component library that works with SSR Declarative Shadow DOM in any framework or Vanilla.js. Thanks to Brisa Web Component Compiler.
TypeScript
1
star