GithubHelp home page GithubHelp logo

aralroca / default-composer Goto Github PK

View Code? Open in Web Editor NEW
462.0 7.0 11.0 145 KB

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

License: MIT License

JavaScript 1.07% TypeScript 98.93%
composer defaults javascript json merge mix nested-objects tree typescript

default-composer's Introduction

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

๐Ÿš‡
Josu Martinez
Josu Martinez

๐Ÿ›

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

default-composer's People

Contributors

allcontributors[bot] avatar aralroca avatar leeferwagen avatar namhtpyn avatar robinpokorny avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

default-composer's Issues

Module not found: Default condition should be last one

First of all: thank you for this nice tiny lib! ๐Ÿ‘

What version of this package are you using?
0.5.0

What operating system, Node.js, and npm version?
node: v18.15.0, yarn: 4.0.0-rc.45

What happened?
I would like to use default-composer in a NextJS-Project and got the following error on importing:

next:dev: Module not found: Default condition should be last one
...
next:dev: > 4 | import { defaultComposer } from "default-composer";

Accoording to Node-Specification about conditional exports:

"default" - the generic fallback that always matches. Can be a CommonJS or ES module file. This condition should always come last.

I tried to change it locally from:

  "exports": {
    "require": "./dist/index.js",
    "default": "./dist/index.modern.mjs",
    "types": "./dist/index.d.ts"
  }

to

"exports": {
    "require": "./dist/index.js",
    "types": "./dist/index.d.ts",
    "default": "./dist/index.modern.mjs"
  }

and the error is gone.

Could you please have a look.

failed to compile in my React app

"default-composer": "^0.4.0"

NODE v16.13.0 NPM 16.13.0 (Currently using 64-bit executable)

Failed to compile on npm start

Failed to compile.

Module parse failed: Unexpected token (30:33)
| },
| p = o(b),

    s = e.isDefaultableValue?.(_objectSpread({}, b, {

| defaultableValue: p
| })) ?? p;

I expected the app to start

Sorry I cannot submit pull request due to NDA

Install as ES module

What problem do you want to solve?
Use this module in a non npm/yarn setup.

Proposed use case:

Use this library as a <script type="module" import directly in the browser.

Are you willing to submit a pull request to implement this change?
Maybe with some guidance.

Default-composer lost type with mathjs

What version of this package are you using?
0.5.1

What operating system, Node.js, and npm version?
Windows, node 18.15.0, npm 9.6.3

What happened?
Passing through default-composer make object to lose methods and other attributes
See code below:

import { unit, isUnit } from "mathjs";
import { defaultComposer } from "default-composer";

const def = {
  a: unit(0, "mm"),
  b: unit(0, "mm"),
  c: unit(0, "mm"),
};

const dim = {
  a: unit(1, "mm"),
  b: unit(2, "mm"),
  c: unit(3, "mm"),
};

console.log(isUnit(dim.a)); // returns true since a is of type mathjs.Unit
const full = defaultComposer(def, dim);
console.log(isUnit(full.a)); // returns false since a is missing of some attributes of mathjs.Unit

I think that during the 'compose' function, you not check for methods (aka functions) on object and (maybe) other stuffs. This make a complex object to lose some attributes.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.