Skip to content

Commit

Permalink
Add config for empty checker (#4)
Browse files Browse the repository at this point in the history
* add config for emptyChecker

* format
  • Loading branch information
aralroca committed May 28, 2023
1 parent 541ae5e commit b31e080
Show file tree
Hide file tree
Showing 6 changed files with 234 additions and 139 deletions.
20 changes: 10 additions & 10 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ In the interest of fostering an open and welcoming environment, we as contributo

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Expand Down
128 changes: 75 additions & 53 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
</h1>
</div>


_A **tiny** (300B) **JavaScript library** that allows you to set **default values** for **nested objects**_

[![npm version](https://badge.fury.io/js/default-composer.svg)](https://badge.fury.io/js/default-composer)
Expand All @@ -14,14 +13,17 @@ _A **tiny** (300B) **JavaScript library** that allows you to set **default value
[![Maintenance Status](https://badgen.net/badge/maintenance/active/green)](https://github.com/aralroca/default-composer#maintenance-status)
[![Weekly downloads](https://badgen.net/npm/dw/default-composer?color=blue)](https://www.npmjs.com/package/default-composer)
[![PRs Welcome][badge-prwelcome]][prwelcome]<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->

<!-- ALL-CONTRIBUTORS-BADGE:END -->

[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.

## Installation

You can install "default-composer" using npm:

```bh
Expand All @@ -36,41 +38,42 @@ yarn add default-composer

## Usage

To use "default-composer", simply require 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:
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:

```js
import defaultComposer from 'default-composer';
import { defaultComposer } from "default-composer";

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

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

const result = defaultComposer(defaults, originalObject);

console.log(result);
```

This will output:

```js
Expand All @@ -94,48 +97,46 @@ This will output:

## API

### `defaultComposer`

```js
defaultComposer(defaults, object1[, object2, ...])
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.

```js
defaultComposer(priority3, priority2, priority1)
```

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
**Example**:

```js
import defaultComposer from 'default-composer';
import { defaultComposer } from "default-composer";

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

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

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

const result = defaultComposer(defaultsPriority2, defaultsPriority1, object);
Expand All @@ -159,6 +160,27 @@ This will output:
}
```

### `setConfig`

`setConfig` is a function that allows you to set configuration options for `defaultComposer`. Currently, the only configuration option available is `emptyChecker`, which is a function that determines whether a value should be considered empty or not. By default, is detected as empty when is null, undefined, an empty string, an empty array, or an empty object. However, you can use `setConfig` to provide your own implementation of `emptyChecker` if you need to customize this behavior.

Here is an example of how you can use `setConfig`:

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

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

setConfig({ emptyChecker: 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' }
```

## 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.
Expand All @@ -167,36 +189,36 @@ Example:

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

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

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

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

defaultComposer<User>(defaults, object)
defaultComposer<User>(defaults, object);
```

## Contributing
Expand Down
6 changes: 3 additions & 3 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
'@babel/preset-typescript',
["@babel/preset-env", { targets: { node: "current" } }],
"@babel/preset-typescript",
],
};
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "default-composer",
"version": "0.1.3",
"version": "0.2.0",
"description": "A JavaScript library that allows you to set default values for nested objects",
"main": "dist/index.js",
"umd:main": "dist/index.umd.js",
Expand Down Expand Up @@ -39,6 +39,7 @@
"test:watch": "jest ./tests --watch",
"build": "microbundle",
"dev": "microbundle watch",
"format": "npx prettier --write .",
"prepublish": "yarn build"
},
"devDependencies": {
Expand Down
Loading

0 comments on commit b31e080

Please sign in to comment.