├── .gitignore ├── bun.lockb ├── babel.config.js ├── .github └── workflows │ └── test.yml ├── LICENSE ├── package.json ├── .all-contributorsrc ├── CODE_OF_CONDUCT.md ├── src ├── index.ts └── index.test.ts ├── CONTRIBUTING.md ├── logo.svg └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules -------------------------------------------------------------------------------- /bun.lockb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aralroca/default-composer/HEAD/bun.lockb -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | ["@babel/preset-env", { targets: { node: "current" } }], 4 | "@babel/preset-typescript", 5 | ], 6 | }; 7 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | - name: Bunjs 16 | uses: oven-sh/setup-bun@v1 17 | with: 18 | bun-version: "0.6.12" 19 | - name: Install dependencies 20 | run: bun install 21 | - run: bun run build 22 | - run: bun run test 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | MIT License 4 | 5 | Copyright (c) 2023 Aral Roca Gomez 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy 8 | of this software and associated documentation files (the "Software"), to deal 9 | in the Software without restriction, including without limitation the rights 10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | copies of the Software, and to permit persons to whom the Software is 12 | furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | SOFTWARE. -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "default-composer", 3 | "version": "0.6.0", 4 | "description": "A JavaScript library that allows you to set default values for nested objects", 5 | "main": "dist/index.js", 6 | "umd:main": "dist/index.umd.js", 7 | "module": "dist/index.m.js", 8 | "exports": { 9 | "require": "./dist/index.js", 10 | "types": "./dist/index.d.ts", 11 | "default": "./dist/index.modern.mjs" 12 | }, 13 | "files": [ 14 | "dist" 15 | ], 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/aralroca/default-composer.git" 19 | }, 20 | "keywords": [ 21 | "default", 22 | "composer", 23 | "merge", 24 | "mix", 25 | "nested", 26 | "defaults", 27 | "json", 28 | "tree", 29 | "javascript", 30 | "typescript" 31 | ], 32 | "author": "Aral Roca ", 33 | "license": "MIT", 34 | "bugs": { 35 | "url": "https://github.com/aralroca/default-composer/issues" 36 | }, 37 | "homepage": "https://github.com/aralroca/default-composer#readme", 38 | "scripts": { 39 | "test": "bun test src/index.test.ts", 40 | "test:watch": "bun --watch test src/index.test.ts", 41 | "build": "microbundle", 42 | "dev": "microbundle watch", 43 | "format": "npx prettier --write .", 44 | "prepublish": "bun run build" 45 | }, 46 | "devDependencies": { 47 | "@babel/preset-typescript": "7.21.5", 48 | "microbundle": "0.15.1" 49 | } 50 | } -------------------------------------------------------------------------------- /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "files": ["README.md"], 3 | "imageSize": 100, 4 | "commit": false, 5 | "commitType": "docs", 6 | "commitConvention": "angular", 7 | "contributors": [ 8 | { 9 | "login": "aralroca", 10 | "name": "Aral Roca Gomez", 11 | "avatar_url": "https://avatars.githubusercontent.com/u/13313058?v=4", 12 | "profile": "https://aralroca.com", 13 | "contributions": ["code", "maintenance"] 14 | }, 15 | { 16 | "login": "robinpokorny", 17 | "name": "Robin Pokorny", 18 | "avatar_url": "https://avatars.githubusercontent.com/u/68341?v=4", 19 | "profile": "http://robinpokorny.com", 20 | "contributions": ["code"] 21 | }, 22 | { 23 | "login": "leeferwagen", 24 | "name": "Muslim Idris", 25 | "avatar_url": "https://avatars.githubusercontent.com/u/1287545?v=4", 26 | "profile": "https://github.com/leeferwagen", 27 | "contributions": ["code"] 28 | }, 29 | { 30 | "login": "namhtpyn", 31 | "name": "namhtpyn", 32 | "avatar_url": "https://avatars.githubusercontent.com/u/16488178?v=4", 33 | "profile": "https://github.com/namhtpyn", 34 | "contributions": ["infra"] 35 | }, 36 | { 37 | "login": "Josuto", 38 | "name": "Josu Martinez", 39 | "avatar_url": "https://avatars.githubusercontent.com/u/6097850?v=4", 40 | "profile": "https://github.com/Josuto", 41 | "contributions": ["bug"] 42 | } 43 | ], 44 | "contributorsPerLine": 7, 45 | "skipCi": true, 46 | "repoType": "github", 47 | "repoHost": "https://github.com", 48 | "projectName": "default-composer", 49 | "projectOwner": "aralroca" 50 | } 51 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | - Using welcoming and inclusive language 12 | - Being respectful of differing viewpoints and experiences 13 | - Gracefully accepting constructive criticism 14 | - Focusing on what is best for the community 15 | - Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | - Trolling, insulting/derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at contact@aralroca.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export type isDefaultableValueInputType = { 2 | defaultableValue: boolean; 3 | key: PropertyKey; 4 | value: unknown; 5 | }; 6 | 7 | export type isDefaultableValueType = ({ 8 | defaultableValue, 9 | key, 10 | value, 11 | }: isDefaultableValueInputType) => boolean; 12 | 13 | export type Config = { 14 | isDefaultableValue?: isDefaultableValueType; 15 | mergeArrays?: boolean; 16 | }; 17 | 18 | let config: Config = {}; 19 | 20 | export function setConfig(newConfig: Config): void { 21 | config = newConfig; 22 | } 23 | 24 | export function defaultComposer(...args: Partial[]): T { 25 | return args.reduce(compose, args[0]) as T; 26 | } 27 | 28 | function compose(defaults: Partial, obj: Partial): Partial { 29 | const result: Partial = {}; 30 | const allKeys = new Set([defaults, obj].flatMap(getAllKeys)); 31 | 32 | for (let key of allKeys) { 33 | const defaultsValue = defaults[key]; 34 | const originalObjectValue = hasOwn(obj, key) ? obj[key] : undefined; 35 | const hasDefault = hasOwn(defaults, key); 36 | const checkOptions = { key, value: originalObjectValue }; 37 | const defaultableValue = checkDefaultableValue(checkOptions); 38 | const defaultableValueFromConfig = 39 | config.isDefaultableValue?.({ ...checkOptions, defaultableValue }) ?? 40 | defaultableValue; 41 | 42 | const shouldTakeDefault = hasDefault && defaultableValueFromConfig; 43 | 44 | if ( 45 | shouldTakeDefault && 46 | config.mergeArrays && 47 | Array.isArray(defaultsValue) && 48 | Array.isArray(originalObjectValue) 49 | ) { 50 | if (!defaultsValue.some(isObject)) { 51 | result[key] = [...new Set([...defaultsValue, ...originalObjectValue])]; 52 | continue; 53 | } 54 | 55 | const maxLength = Math.max( 56 | defaultsValue.length, 57 | originalObjectValue.length, 58 | ); 59 | const setOfObjects = new Set(); 60 | 61 | for (let i = 0; i < maxLength; i++) { 62 | setOfObjects.add(compose(defaultsValue[i] ?? {}, originalObjectValue[i] ?? {})); 63 | } 64 | 65 | result[key] = [...setOfObjects]; 66 | 67 | continue; 68 | } 69 | 70 | if (shouldTakeDefault) { 71 | result[key] = defaultsValue; 72 | continue; 73 | } 74 | 75 | if (isObject(defaultsValue) && isObject(originalObjectValue)) { 76 | result[key] = compose(defaultsValue, originalObjectValue); 77 | continue; 78 | } 79 | 80 | result[key] = originalObjectValue; 81 | } 82 | 83 | return result; 84 | } 85 | 86 | function isObject(value: any): boolean { 87 | return ( 88 | typeof value === "object" && 89 | value !== null && 90 | value.constructor === Object && 91 | !Array.isArray(value) 92 | ); 93 | } 94 | 95 | function isEmptyObjectOrArray(object: T): boolean { 96 | if (typeof object !== "object" || object === null || object instanceof Date) 97 | return false; 98 | return getAllKeys(object).length === 0; 99 | } 100 | 101 | function checkDefaultableValue({ value }: { value: unknown }): boolean { 102 | return ( 103 | value === undefined || 104 | value === "" || 105 | value === null || 106 | isEmptyObjectOrArray(value) || 107 | (Boolean(config.mergeArrays) && Array.isArray(value)) 108 | ); 109 | } 110 | 111 | function hasOwn( 112 | obj: Partial>, 113 | key: unknown, 114 | ): key is T { 115 | return Object.prototype.hasOwnProperty.call(obj, key); 116 | } 117 | 118 | function getAllKeys(object: {}): PropertyKey[] { 119 | return [ 120 | ...Object.keys(object), 121 | ...Object.getOwnPropertySymbols(object).filter( 122 | (key) => Object.getOwnPropertyDescriptor(object, key)?.enumerable, 123 | ), 124 | ]; 125 | } 126 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure you are doing the PR to the canary branch. 11 | 2. Write the failing tests about the issue / feature you are working on. 12 | 3. Update the README.md with details of changes to the interface. 13 | 4. You may merge the Pull Request in once you have the approval of at least one maintainer, or if you 14 | do not have permission to do that, you may request the maintainer to merge it for you. 15 | 16 | ## Code of Conduct 17 | 18 | ### Our Pledge 19 | 20 | In the interest of fostering an open and welcoming environment, we as 21 | contributors and maintainers pledge to making participation in our project and 22 | our community a harassment-free experience for everyone, regardless of age, body 23 | size, disability, ethnicity, gender identity and expression, level of experience, 24 | nationality, personal appearance, race, religion, or sexual identity and 25 | orientation. 26 | 27 | ### Our Standards 28 | 29 | Examples of behavior that contributes to creating a positive environment 30 | include: 31 | 32 | - Using welcoming and inclusive language 33 | - Being respectful of differing viewpoints and experiences 34 | - Gracefully accepting constructive criticism 35 | - Focusing on what is best for the community 36 | - Showing empathy towards other community members 37 | 38 | Examples of unacceptable behavior by participants include: 39 | 40 | - The use of sexualized language or imagery and unwelcome sexual attention or 41 | advances 42 | - Trolling, insulting/derogatory comments, and personal or political attacks 43 | - Public or private harassment 44 | - Publishing others' private information, such as a physical or electronic 45 | address, without explicit permission 46 | - Other conduct which could reasonably be considered inappropriate in a 47 | professional setting 48 | 49 | ### Our Responsibilities 50 | 51 | Project maintainers are responsible for clarifying the standards of acceptable 52 | behavior and are expected to take appropriate and fair corrective action in 53 | response to any instances of unacceptable behavior. 54 | 55 | Project maintainers have the right and responsibility to remove, edit, or 56 | reject comments, commits, code, wiki edits, issues, and other contributions 57 | that are not aligned to this Code of Conduct, or to ban temporarily or 58 | permanently any contributor for other behaviors that they deem inappropriate, 59 | threatening, offensive, or harmful. 60 | 61 | ### Scope 62 | 63 | This Code of Conduct applies both within project spaces and in public spaces 64 | when an individual is representing the project or its community. Examples of 65 | representing a project or community include using an official project e-mail 66 | address, posting via an official social media account, or acting as an appointed 67 | representative at an online or offline event. Representation of a project may be 68 | further defined and clarified by project maintainers. 69 | 70 | ### Enforcement 71 | 72 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 73 | reported by contacting the project team at contact@aralroca.com. All 74 | complaints will be reviewed and investigated and will result in a response that 75 | is deemed necessary and appropriate to the circumstances. The project team is 76 | obligated to maintain confidentiality with regard to the reporter of an incident. 77 | Further details of specific enforcement policies may be posted separately. 78 | 79 | Project maintainers who do not follow or enforce the Code of Conduct in good 80 | faith may face temporary or permanent repercussions as determined by other 81 | members of the project's leadership. 82 | 83 | ### Attribution 84 | 85 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 86 | available at [http://contributor-covenant.org/version/1/4][version] 87 | 88 | [homepage]: http://contributor-covenant.org 89 | [version]: http://contributor-covenant.org/version/1/4/ 90 | -------------------------------------------------------------------------------- /logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 10 | 11 | 29 | 38 | 47 | 48 | 49 | 58 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /src/index.test.ts: -------------------------------------------------------------------------------- 1 | import { beforeEach, describe, expect, it, mock } from "bun:test"; 2 | import { defaultComposer, setConfig } from "."; 3 | 4 | type Address = { 5 | street?: string; 6 | city?: string; 7 | state?: string; 8 | zip?: string; 9 | }; 10 | 11 | type User = { 12 | name: string; 13 | surname?: string; 14 | isDeveloper?: boolean; 15 | isDesigner?: boolean | null; 16 | age: number | null; 17 | address: Address; 18 | hobbies: string[]; 19 | emails: string[]; 20 | toString: string; 21 | constructor: string | null; 22 | [Symbol.isConcatSpreadable]: boolean; 23 | }; 24 | 25 | describe("defaultComposer", () => { 26 | beforeEach(() => setConfig({})); 27 | 28 | it("should defaultComposer defaults with originalObject", () => { 29 | const defaults = { 30 | name: "Aral 😊", 31 | surname: "", 32 | isDeveloper: true, 33 | isDesigner: false, 34 | age: 33, 35 | address: { 36 | street: "123 Main St", 37 | city: "Anytown", 38 | state: "CA", 39 | }, 40 | emails: ["contact@aralroca.com"], 41 | hobbies: ["programming"], 42 | toString: "I am Aral", 43 | [Symbol.isConcatSpreadable]: false, 44 | } as User; 45 | 46 | const originalObject = { 47 | name: "Aral", 48 | emails: [], 49 | isDesigner: null, 50 | phone: "555555555", 51 | age: null, 52 | address: { 53 | zip: "54321", 54 | }, 55 | hobbies: ["parkour", "computer science", "books", "nature"], 56 | constructor: null, 57 | } as unknown as User; 58 | 59 | const expected = { 60 | name: "Aral", 61 | surname: "", 62 | isDeveloper: true, 63 | isDesigner: false, 64 | emails: ["contact@aralroca.com"], 65 | phone: "555555555", 66 | age: 33, 67 | address: { 68 | street: "123 Main St", 69 | city: "Anytown", 70 | state: "CA", 71 | zip: "54321", 72 | }, 73 | hobbies: ["parkour", "computer science", "books", "nature"], 74 | toString: "I am Aral", 75 | constructor: null, 76 | [Symbol.isConcatSpreadable]: false, 77 | }; 78 | 79 | expect(defaultComposer(defaults, originalObject)).toEqual(expected); 80 | }); 81 | 82 | it("should work with multiple objects", () => { 83 | const defaultsPriority1 = { 84 | name: "Aral 😊", 85 | hobbies: ["reading"], 86 | } as User; 87 | 88 | const defaultsPriority2 = { 89 | name: "Aral 🤔", 90 | age: 33, 91 | address: { 92 | street: "123 Main St", 93 | city: "Anytown", 94 | state: "CA", 95 | zip: "12345", 96 | }, 97 | hobbies: ["reading", "hiking"], 98 | } as User; 99 | 100 | const object = { 101 | address: { 102 | street: "", 103 | city: "Anothercity", 104 | state: "NY", 105 | zip: "", 106 | }, 107 | hobbies: ["running"], 108 | } as User; 109 | 110 | const expected = { 111 | name: "Aral 😊", 112 | age: 33, 113 | address: { 114 | street: "123 Main St", 115 | city: "Anothercity", 116 | state: "NY", 117 | zip: "12345", 118 | }, 119 | hobbies: ["running"], 120 | }; 121 | 122 | expect( 123 | defaultComposer(defaultsPriority2, defaultsPriority1, object), 124 | ).toEqual(expected); 125 | }); 126 | 127 | it("should work with functions inside the object", () => { 128 | const mockFn = mock(); 129 | const defaults = { 130 | test: () => mockFn(), 131 | }; 132 | 133 | const object = { 134 | test: null, 135 | }; 136 | 137 | const output = defaultComposer(defaults, object); 138 | 139 | output.test(); 140 | 141 | expect(mockFn).toHaveBeenCalledTimes(1); 142 | }); 143 | 144 | it("should work with enumerable symbol properties", () => { 145 | const tag = Symbol.for("tag"); 146 | const version = Symbol.for("version"); 147 | const createdAt = Symbol.for("createdAt"); 148 | 149 | const defaults = { 150 | [tag]: "user", 151 | [createdAt]: Date.UTC(2020, 1, 1), 152 | }; 153 | 154 | Object.defineProperty(defaults, version, { value: 1, enumerable: false }); 155 | 156 | const object = { 157 | [createdAt]: Date.UTC(2023, 6, 1), 158 | }; 159 | 160 | const expected = { 161 | [tag]: "user", 162 | [createdAt]: Date.UTC(2023, 6, 1), 163 | }; 164 | 165 | expect(defaultComposer(defaults, object)).toEqual(expected); 166 | }); 167 | 168 | it("should work with a custom isDefaultableValue", () => { 169 | const defaults = { 170 | original: { 171 | shouldKeepOriginal1: "replaced", 172 | shouldKeepOriginal2: "replaced", 173 | }, 174 | mixed: { 175 | shouldTakeDefault1: "replaced", 176 | shouldTakeDefault2: "replaced", 177 | shouldKeepOriginal1: "replaced", 178 | shouldKeepOriginal2: "replaced", 179 | shouldKeepOriginal3: "replaced", 180 | shouldKeepOriginal4: "replaced", 181 | }, 182 | }; 183 | const object = { 184 | original: { 185 | shouldKeepOriginal1: "original", 186 | shouldKeepOriginal2: true, 187 | }, 188 | mixed: { 189 | shouldTakeDefault1: " ", 190 | shouldTakeDefault2: null, 191 | shouldKeepOriginal1: false, 192 | shouldKeepOriginal2: undefined, 193 | shouldKeepOriginal3: [], 194 | shouldKeepOriginal4: {}, 195 | }, 196 | }; 197 | const isNullOrWhitespace = ({ value }) => 198 | value === null || (typeof value === "string" && value.trim() === ""); 199 | 200 | const expected = { 201 | original: { 202 | shouldKeepOriginal1: "original", 203 | shouldKeepOriginal2: true, 204 | }, 205 | mixed: { 206 | shouldTakeDefault1: "replaced", 207 | shouldTakeDefault2: "replaced", 208 | shouldKeepOriginal1: false, 209 | shouldKeepOriginal2: undefined, 210 | shouldKeepOriginal3: [], 211 | shouldKeepOriginal4: {}, 212 | }, 213 | }; 214 | 215 | setConfig({ isDefaultableValue: isNullOrWhitespace }); 216 | 217 | expect(defaultComposer(defaults, object)).toEqual(expected); 218 | }); 219 | 220 | it("should work with a custom isDefaultableValue reusing pre-calculated defaultableValue ", () => { 221 | const defaults = { 222 | original: { 223 | shouldKeepOriginal1: "replaced", 224 | shouldKeepOriginal2: "replaced", 225 | }, 226 | mixed: { 227 | shouldTakeDefault1: "replaced", 228 | shouldTakeDefault2: "replaced", 229 | shouldKeepOriginal1: "replaced", 230 | shouldKeepOriginal2: "replaced", 231 | shouldKeepOriginal3: "replaced", 232 | shouldKeepOriginal4: "replaced", 233 | }, 234 | }; 235 | const object = { 236 | original: { 237 | shouldKeepOriginal1: "original", 238 | shouldKeepOriginal2: true, 239 | }, 240 | mixed: { 241 | shouldTakeDefault1: " ", 242 | shouldTakeDefault2: null, 243 | shouldKeepOriginal1: false, 244 | shouldKeepOriginal2: undefined, 245 | shouldKeepOriginal3: [], 246 | shouldKeepOriginal4: {}, 247 | }, 248 | }; 249 | const isNullOrWhitespace = ({ value, defaultableValue }) => 250 | defaultableValue || (typeof value === "string" && value.trim() === ""); 251 | 252 | const expected = { 253 | original: { 254 | shouldKeepOriginal1: "original", 255 | shouldKeepOriginal2: true, 256 | }, 257 | mixed: { 258 | shouldTakeDefault1: "replaced", 259 | shouldTakeDefault2: "replaced", 260 | shouldKeepOriginal1: false, 261 | shouldKeepOriginal2: "replaced", 262 | shouldKeepOriginal3: "replaced", 263 | shouldKeepOriginal4: "replaced", 264 | }, 265 | }; 266 | 267 | setConfig({ isDefaultableValue: isNullOrWhitespace }); 268 | 269 | expect(defaultComposer(defaults, object)).toEqual(expected); 270 | }); 271 | 272 | it("should merge arrays when config.mergeArrays is true", () => { 273 | const defaults = { 274 | hobbies: ["reading"], 275 | another: ["another"], 276 | nested: { 277 | example: ["a", "b", "c"], 278 | nums: [1, 2, 3], 279 | objects: [{ a: 1 }, { b: 2 }], 280 | notDefaultableKey: ["defaultValue"], 281 | }, 282 | }; 283 | 284 | const object = { 285 | hobbies: ["running"], 286 | nested: { 287 | example: ["a", "d", "e"], 288 | nums: [1, 4, 5], 289 | objects: [{ c: 1 }, { d: 2 }, { e: 3 }], 290 | notDefaultableKey: ["shouldNotBeMerged"], 291 | }, 292 | }; 293 | 294 | const expected = { 295 | hobbies: ["reading", "running"], 296 | another: ["another"], 297 | nested: { 298 | example: ["a", "b", "c", "d", "e"], 299 | nums: [1, 2, 3, 4, 5], 300 | objects: [ 301 | { a: 1, c: 1 }, 302 | { b: 2, d: 2 }, 303 | { e: 3 } 304 | ], 305 | notDefaultableKey: ["shouldNotBeMerged"], 306 | }, 307 | }; 308 | 309 | const isDefaultableValue = ({ defaultableValue, key }) => 310 | defaultableValue && key !== "notDefaultableKey"; 311 | 312 | setConfig({ mergeArrays: true, isDefaultableValue }); 313 | 314 | expect(defaultComposer(defaults, object)).toEqual(expected); 315 | }); 316 | 317 | it("should respect the Date object", () => { 318 | const defaults = { 319 | date: new Date(), 320 | range: { 321 | startDate: new Date(2020, 1, 1), 322 | endDate: new Date(2020, 1, 2), 323 | }, 324 | }; 325 | 326 | const object = { 327 | date: new Date(2020, 1, 1), 328 | anotherDate: new Date(2020, 2, 1), 329 | }; 330 | 331 | const output = defaultComposer(defaults, object); 332 | 333 | const expected = { 334 | date: new Date(2020, 1, 1), 335 | anotherDate: new Date(2020, 2, 1), 336 | range: { 337 | startDate: new Date(2020, 1, 1), 338 | endDate: new Date(2020, 1, 2), 339 | }, 340 | }; 341 | 342 | expect(output).toStrictEqual(expected); 343 | }); 344 | 345 | it("should respect instance of any class", () => { 346 | class TestClass { 347 | constructor(public name: string) { } 348 | } 349 | 350 | const defaults = { 351 | test: new TestClass("test"), 352 | }; 353 | 354 | const object = { 355 | test: new TestClass("test2"), 356 | }; 357 | 358 | const output = defaultComposer(defaults, object); 359 | 360 | const expected = { 361 | test: new TestClass("test2"), 362 | }; 363 | 364 | expect(output).toStrictEqual(expected); 365 | }); 366 | }); 367 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | Default composer logo 3 |

4 |
Default composer
5 |

6 |
7 | 8 | _A **tiny** (~500B) **JavaScript library** that allows you to set **default values** for **nested objects**_ 9 | 10 | [![npm version](https://badge.fury.io/js/default-composer.svg)](https://badge.fury.io/js/default-composer) 11 | [![gzip size](https://img.badgesize.io/https://unpkg.com/default-composer?compression=gzip&label=gzip)](https://unpkg.com/default-composer) 12 | [![CI Status](https://github.com/aralroca/default-composer/actions/workflows/test.yml/badge.svg)](https://github.com/aralroca/default-composer/actions/workflows/test.yml) 13 | [![Maintenance Status](https://badgen.net/badge/maintenance/active/green)](https://github.com/aralroca/default-composer#maintenance-status) 14 | [![Weekly downloads](https://badgen.net/npm/dw/default-composer?color=blue)](https://www.npmjs.com/package/default-composer) 15 | [![PRs Welcome][badge-prwelcome]][prwelcome] 16 | [![All Contributors](https://img.shields.io/badge/all_contributors-5-orange.svg?style=flat-square)](#contributors-) 17 | 18 | 19 | 20 | [badge-prwelcome]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square 21 | 22 | [prwelcome]: http://makeapullrequest.com 23 | 24 | "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. 25 | 26 | **Content**: 27 | 28 | - [1. Installation](#installation) 29 | - [2. Usage](#usage) 30 | - [3. API](#api) 31 | - [`defaultComposer`](#defaultcomposer) 32 | - [`setConfig`](#setconfig) 33 | - [`isDefaultableValue`](#isdefaultablevalue) 34 | - [`mergeArrays`](#mergearrays) 35 | - [4. TypeScript](#typescript) 36 | - [5. Contributing](#contributing) 37 | - [6. License](#license) 38 | - [7. Credits](#credits) 39 | - [8. Contributors](#contributors-) 40 | 41 | ## Installation 42 | 43 | You can install "default-composer" using npm: 44 | 45 | ```bh 46 | npm install default-composer 47 | ``` 48 | 49 | or with yarn: 50 | 51 | ```bh 52 | yarn add default-composer 53 | ``` 54 | 55 | ## Usage 56 | 57 | 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: 58 | 59 | ```js 60 | import { defaultComposer } from "default-composer"; 61 | 62 | const defaults = { 63 | name: "Aral 😊", 64 | surname: "", 65 | isDeveloper: true, 66 | isDesigner: false, 67 | age: 33, 68 | address: { 69 | street: "123 Main St", 70 | city: "Anytown", 71 | state: "CA", 72 | }, 73 | emails: ["contact@aralroca.com"], 74 | hobbies: ["programming"], 75 | }; 76 | 77 | const originalObject = { 78 | name: "Aral", 79 | emails: [], 80 | phone: "555555555", 81 | age: null, 82 | address: { 83 | zip: "54321", 84 | }, 85 | hobbies: ["parkour", "computer science", "books", "nature"], 86 | }; 87 | 88 | const result = defaultComposer(defaults, originalObject); 89 | 90 | console.log(result); 91 | ``` 92 | 93 | This will output: 94 | 95 | ```js 96 | { 97 | name: 'Aral', 98 | surname: '', 99 | isDeveloper: true, 100 | isDesigner: false, 101 | emails: ['contact@aralroca.com'], 102 | phone: '555555555', 103 | age: 33, 104 | address: { 105 | street: '123 Main St', 106 | city: 'Anytown', 107 | state: 'CA', 108 | zip: '54321' 109 | }, 110 | hobbies: ['parkour', 'computer science', 'books', 'nature'], 111 | } 112 | ``` 113 | 114 | ## API 115 | 116 | ### `defaultComposer` 117 | 118 | ```js 119 | defaultComposer(defaultsPriorityN, [..., defaultsPriority2, defaultsPriority1, objectWithData]) 120 | ``` 121 | 122 | 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. 123 | 124 | 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. 125 | 126 | **Example**: 127 | 128 | ```js 129 | import { defaultComposer } from "default-composer"; 130 | 131 | const defaultsPriority1 = { 132 | name: "Aral 😊", 133 | hobbies: ["reading"], 134 | }; 135 | 136 | const defaultsPriority2 = { 137 | name: "Aral 🤔", 138 | age: 33, 139 | address: { 140 | street: "123 Main St", 141 | city: "Anytown", 142 | state: "CA", 143 | zip: "12345", 144 | }, 145 | hobbies: ["reading", "hiking"], 146 | }; 147 | 148 | const object = { 149 | address: { 150 | street: "", 151 | city: "Anothercity", 152 | state: "NY", 153 | zip: "", 154 | }, 155 | hobbies: ["running"], 156 | }; 157 | 158 | const result = defaultComposer(defaultsPriority2, defaultsPriority1, object); 159 | 160 | console.log(result); 161 | ``` 162 | 163 | This will output: 164 | 165 | ```js 166 | { 167 | name: 'Aral 😊', 168 | age: 33, 169 | address: { 170 | street: '123 Main St', 171 | city: 'Anothercity', 172 | state: 'NY', 173 | zip: '12345' 174 | }, 175 | hobbies: ['running'] 176 | } 177 | ``` 178 | 179 | ### `setConfig` 180 | 181 | `setConfig` is a function that allows you to set configuration options for `defaultComposer`. 182 | 183 | This is the available configuration: 184 | 185 | - **`isDefaultableValue`**, is a function that determines whether a value should be considered defaultable or not. 186 | - **`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`. 187 | 188 | #### `isDefaultableValue` 189 | 190 | You can use `setConfig` to provide your own implementation of `isDefaultableValue` if you need to customize this behavior. 191 | 192 | ```ts 193 | type IsDefaultableValueParams = ({ 194 | key, 195 | value, 196 | defaultableValue, 197 | }: { 198 | key: string; 199 | value: unknown; 200 | defaultableValue: boolean; // In case you want to re-use the default behavior 201 | }) => boolean; 202 | ``` 203 | 204 | 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`. 205 | 206 | Here is an example of how you can use `setConfig`: 207 | 208 | ```ts 209 | import { defaultComposer, setConfig } from "default-composer"; 210 | 211 | const isNullOrWhitespace = ({ key, value }) => { 212 | return value === null || (typeof value === "string" && value.trim() === ""); 213 | }; 214 | 215 | setConfig({ isDefaultableValue: isNullOrWhitespace }); 216 | 217 | const defaults = { example: "replaced", anotherExample: "also replaced" }; 218 | const originalObject = { example: " ", anotherExample: null }; 219 | const result = defaultComposer(defaults, originalObject); 220 | console.log(result); // { example: 'replaced', anotherExample: 'also replaced' } 221 | ``` 222 | 223 | Here is another example of how you can use `setConfig` reusing the `defaultableValue`: 224 | 225 | ```ts 226 | import { defaultComposer, setConfig } from "default-composer"; 227 | 228 | setConfig({ 229 | isDefaultableValue({ key, value, defaultableValue }) { 230 | return ( 231 | defaultableValue || (typeof value === "string" && value.trim() === "") 232 | ); 233 | }, 234 | }); 235 | 236 | const defaults = { example: "replaced", anotherExample: "also replaced" }; 237 | const originalObject = { example: " ", anotherExample: null }; 238 | const result = defaultComposer(defaults, originalObject); 239 | console.log(result); // { example: 'replaced', anotherExample: 'also replaced' } 240 | ``` 241 | 242 | #### `mergeArrays` 243 | 244 | Example to merge arrays: 245 | 246 | ```ts 247 | const defaults = { 248 | hobbies: ["reading"], 249 | }; 250 | 251 | const object = { 252 | hobbies: ["running"], 253 | }; 254 | setConfig({ mergeArrays: true}); 255 | 256 | defaultComposer(defaults, object)) // { hobbies: ["reading", "running"]} 257 | ``` 258 | 259 | ## TypeScript 260 | 261 | 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. 262 | 263 | Example: 264 | 265 | ```ts 266 | type Addres = { 267 | street: string; 268 | city: string; 269 | state: string; 270 | zip: string; 271 | }; 272 | 273 | type User = { 274 | name: string; 275 | age: number; 276 | address: Address; 277 | hobbies: string[]; 278 | }; 279 | 280 | const defaults = { 281 | name: "Aral 😊", 282 | hobbies: ["reading"], 283 | }; 284 | 285 | const object = { 286 | age: 33, 287 | address: { 288 | street: "", 289 | city: "Anothercity", 290 | state: "NY", 291 | zip: "", 292 | }, 293 | hobbies: [], 294 | }; 295 | 296 | defaultComposer(defaults, object); 297 | ``` 298 | 299 | ## Contributing 300 | 301 | 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. 302 | 303 | ## License 304 | 305 | "default-composer" is licensed under the MIT license. See [LICENSE](LICENSE) for more information. 306 | 307 | ## Credits 308 | 309 | "default-composer" was created by [Aral Roca](https://github.com/aralroca). 310 | 311 | follow on Twitter 313 | 314 | ## Contributors ✨ 315 | 316 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 |
Aral Roca Gomez
Aral Roca Gomez

💻 🚧
Robin Pokorny
Robin Pokorny

💻
Muslim Idris
Muslim Idris

💻
namhtpyn
namhtpyn

🚇
Josu Martinez
Josu Martinez

🐛
332 | 333 | 334 | 335 | 336 | 337 | 338 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! 339 | --------------------------------------------------------------------------------