├── .all-contributorsrc ├── .editorconfig ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── bug_types.yml │ └── feature_request.yml ├── pull_request_template.md └── workflows │ └── workflow.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── ava.config.js ├── eslint.config.js ├── gulpfile.js ├── package-lock.json ├── package.json ├── prettier.config.js ├── src ├── find.js ├── find.test.js ├── flatten.js ├── flatten.test.js ├── helpers │ ├── functions.test.js │ ├── inherited.test.js │ ├── mutate.test.js │ ├── output.test.js │ └── validate.test.js ├── include │ ├── exclude.js │ ├── exclude.test.js │ ├── include.js │ ├── include.test.js │ ├── pick.js │ ├── pick.test.js │ └── reduce.js ├── main.d.ts ├── main.js ├── main.test-d.ts ├── map.js ├── map.test.js ├── merge │ ├── array.js │ ├── array.test.js │ ├── common.js │ ├── object.js │ └── object.test.js └── validate.js └── tsconfig.json /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "projectName": "wild-wild-utils", 3 | "projectOwner": "ehmicky", 4 | "repoType": "github", 5 | "repoHost": "https://github.com", 6 | "files": [ 7 | "README.md" 8 | ], 9 | "imageSize": 100, 10 | "commit": true, 11 | "linkToUsage": false, 12 | "contributors": [ 13 | { 14 | "login": "ehmicky", 15 | "name": "ehmicky", 16 | "avatar_url": "https://avatars2.githubusercontent.com/u/8136211?v=4", 17 | "profile": "https://fosstodon.org/@ehmicky", 18 | "contributions": [ 19 | "code", 20 | "design", 21 | "ideas", 22 | "doc" 23 | ] 24 | } 25 | ], 26 | "contributorsPerLine": 7, 27 | "skipCi": true, 28 | "commitConvention": "none" 29 | } 30 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | end_of_line = lf 7 | charset = utf-8 8 | max_line_length = 80 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: Bug report 2 | description: Report a bug 3 | title: Please replace with a clear and descriptive title 4 | labels: [bug] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: Thanks for reporting this bug! 9 | - type: checkboxes 10 | attributes: 11 | label: Guidelines 12 | options: 13 | - label: 14 | Please search other issues to make sure this bug has not already 15 | been reported. 16 | required: true 17 | - label: 18 | If this is related to a typo or the documentation being unclear, 19 | please click on the relevant page's `Edit` button (pencil icon) and 20 | suggest a correction instead. 21 | required: true 22 | - type: textarea 23 | attributes: 24 | label: Describe the bug 25 | placeholder: A clear and concise description of what the bug is. 26 | validations: 27 | required: true 28 | - type: textarea 29 | attributes: 30 | label: Steps to reproduce 31 | placeholder: | 32 | Step-by-step instructions on how to reproduce the behavior. 33 | Example: 34 | 1. Type the following command: [...] 35 | 2. etc. 36 | validations: 37 | required: true 38 | - type: textarea 39 | attributes: 40 | label: Configuration 41 | placeholder: Command line options and/or configuration file, if any. 42 | validations: 43 | required: true 44 | - type: textarea 45 | attributes: 46 | label: Environment 47 | description: | 48 | Enter the following command in a terminal and copy/paste its output: 49 | ```bash 50 | npx envinfo --system --binaries --browsers --npmPackages wild-wild-utils 51 | ``` 52 | validations: 53 | required: true 54 | - type: checkboxes 55 | attributes: 56 | label: Pull request (optional) 57 | description: 58 | Pull requests are welcome! If you would like to help us fix this bug, 59 | please check our [contributions 60 | guidelines](../blob/main/CONTRIBUTING.md). 61 | options: 62 | - label: I can submit a pull request. 63 | required: false 64 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_types.yml: -------------------------------------------------------------------------------- 1 | name: Bug report (TypeScript types) 2 | description: Report a bug about TypeScript types 3 | title: Please replace with a clear and descriptive title 4 | labels: [bug] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: Thanks for reporting this bug! 9 | - type: checkboxes 10 | attributes: 11 | label: Guidelines 12 | options: 13 | - label: 14 | Please search other issues to make sure this bug has not already 15 | been reported. 16 | required: true 17 | - type: textarea 18 | attributes: 19 | label: Describe the bug 20 | placeholder: A clear and concise description of what the bug is. 21 | validations: 22 | required: true 23 | - type: textarea 24 | attributes: 25 | label: Steps to reproduce 26 | description: | 27 | Please reproduce the bug using the [TypeScript playground](https://www.typescriptlang.org/play) or [Bug workbench](https://www.typescriptlang.org/dev/bug-workbench), then paste the URL here. 28 | validations: 29 | required: true 30 | - type: textarea 31 | attributes: 32 | label: Environment 33 | description: | 34 | Enter the following command in a terminal and copy/paste its output: 35 | ```bash 36 | npx envinfo --system --binaries --browsers --npmPackages wild-wild-utils,typescript --npmGlobalPackages typescript 37 | ``` 38 | validations: 39 | required: true 40 | - type: checkboxes 41 | attributes: 42 | label: Pull request (optional) 43 | description: 44 | Pull requests are welcome! If you would like to help us fix this bug, 45 | please check our [contributions 46 | guidelines](../blob/main/CONTRIBUTING.md). 47 | options: 48 | - label: I can submit a pull request. 49 | required: false 50 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Suggest an idea for this project 3 | title: Please replace with a clear and descriptive title 4 | labels: [enhancement] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: Thanks for suggesting a new feature! 9 | - type: checkboxes 10 | attributes: 11 | label: Guidelines 12 | options: 13 | - label: 14 | Please search other issues to make sure this feature has not already 15 | been requested. 16 | required: true 17 | - type: textarea 18 | attributes: 19 | label: Which problem is this feature request solving? 20 | placeholder: I'm always frustrated when [...] 21 | validations: 22 | required: true 23 | - type: textarea 24 | attributes: 25 | label: Describe the solution you'd like 26 | placeholder: This could be fixed by [...] 27 | validations: 28 | required: true 29 | - type: checkboxes 30 | attributes: 31 | label: Pull request (optional) 32 | description: 33 | Pull requests are welcome! If you would like to help us fix this bug, 34 | please check our [contributions 35 | guidelines](../blob/main/CONTRIBUTING.md). 36 | options: 37 | - label: I can submit a pull request. 38 | required: false 39 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 🎉 Thanks for sending this pull request! 🎉 2 | 3 | Please make sure the title is clear and descriptive. 4 | 5 | If you are fixing a typo or documentation, please skip these instructions. 6 | 7 | Otherwise please fill in the sections below. 8 | 9 | **Which problem is this pull request solving?** 10 | 11 | Example: I'm always frustrated when [...] 12 | 13 | **List other issues or pull requests related to this problem** 14 | 15 | Example: This fixes #5012 16 | 17 | **Describe the solution you've chosen** 18 | 19 | Example: I've fixed this by [...] 20 | 21 | **Describe alternatives you've considered** 22 | 23 | Example: Another solution would be [...] 24 | 25 | **Checklist** 26 | 27 | Please add a `x` inside each checkbox: 28 | 29 | - [ ] I have read the [contribution guidelines](../blob/main/CONTRIBUTING.md). 30 | - [ ] I have added tests (we are enforcing 100% test coverage). 31 | - [ ] I have added documentation in the `README.md`, the `docs` directory (if 32 | any) 33 | - [ ] The status checks are successful (continuous integration). Those can be 34 | seen below. 35 | -------------------------------------------------------------------------------- /.github/workflows/workflow.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: [push, pull_request] 3 | jobs: 4 | combinations: 5 | uses: ehmicky/dev-tasks/.github/workflows/build.yml@main 6 | secrets: inherit 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.swp 3 | npm-debug.log 4 | node_modules 5 | /core 6 | .eslintcache 7 | .lycheecache 8 | .npmrc 9 | .yarn-error.log 10 | !.github/ 11 | /coverage 12 | /build 13 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 6.0.1 2 | 3 | ## Documentation 4 | 5 | - Improve documentation in `README.md` 6 | 7 | # 6.0.0 8 | 9 | ## Breaking changes 10 | 11 | - Minimal supported Node.js version is now `18.18.0` 12 | 13 | # 5.0.0 14 | 15 | ## Breaking changes 16 | 17 | - Minimal supported Node.js version is now `16.17.0` 18 | 19 | # 4.9.0 20 | 21 | ## Features 22 | 23 | - Improve TypeScript types 24 | 25 | # 4.8.0 26 | 27 | ## Features 28 | 29 | - Improve tree-shaking support 30 | 31 | # 4.7.0 32 | 33 | ## Features 34 | 35 | - Add browser support 36 | 37 | # 4.6.0 38 | 39 | ## Features 40 | 41 | - Add support for [`sort` option](README.md#sort) with 42 | [`flatten()` method](README.md#flattentarget-options) 43 | 44 | # 4.5.0 45 | 46 | ## Features 47 | 48 | - Add [`flatten()` method](README.md#flattentarget-options) which flattens deep 49 | properties to shallow properties with dot-delimited paths 50 | 51 | # 4.4.0 52 | 53 | ## Features 54 | 55 | - Add [`shallowArrays` option](README.md#shallowarrays) which prevents recursing 56 | on arrays 57 | 58 | # 4.3.0 59 | 60 | ## Features 61 | 62 | - Reduce npm package size by 56%, from 432kB to 192kB 63 | 64 | # 4.2.0 65 | 66 | ## Features 67 | 68 | - Reduce npm package size by 67%, from ~1290kB to ~432kB 69 | 70 | # 4.1.0 71 | 72 | ## Features 73 | 74 | - Reduce npm package size 75 | 76 | # 4.0.0 77 | 78 | ## Breaking changes 79 | 80 | - The 81 | [`merge()`](https://github.com/ehmicky/declarative-merge#mergetarget-query-value-options) 82 | method has been improved: 83 | - Merging is now deep by default 84 | - Merging mode can be changed to 85 | [`"shallow"`](https://github.com/ehmicky/declarative-merge#shallow-merge), 86 | [`"set"`](https://github.com/ehmicky/declarative-merge#no-merge) or 87 | [`"delete"`](https://github.com/ehmicky/declarative-merge#delete) using a 88 | [`_merge` property](https://github.com/ehmicky/declarative-merge#nesting) 89 | - Arrays 90 | [can now be merged using objects](https://github.com/ehmicky/declarative-merge#arrays) 91 | where the keys are the 92 | [array indices](https://github.com/ehmicky/declarative-merge#update). Items 93 | can be [updated](https://github.com/ehmicky/declarative-merge#update), 94 | [merged](https://github.com/ehmicky/declarative-merge#merge), 95 | [added](https://github.com/ehmicky/declarative-merge#add), 96 | [inserted](https://github.com/ehmicky/declarative-merge#insert), 97 | [appended](https://github.com/ehmicky/declarative-merge#append), 98 | [prepended](https://github.com/ehmicky/declarative-merge#prepend) or 99 | [deleted](https://github.com/ehmicky/declarative-merge#delete-1). 100 | - The merged value can now be of any type 101 | - TypeScript types have been updated accordingly 102 | 103 | # 3.0.0 104 | 105 | ## Breaking changes 106 | 107 | - Minimal supported Node.js version is now `14.18.0` 108 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | This text is available in 4 | [many other languages](https://www.contributor-covenant.org/translations). 5 | 6 | ## Our Pledge 7 | 8 | We as members, contributors, and leaders pledge to make participation in our 9 | community a harassment-free experience for everyone, regardless of age, body 10 | size, visible or invisible disability, ethnicity, sex characteristics, gender 11 | identity and expression, level of experience, education, socio-economic status, 12 | nationality, personal appearance, race, religion, or sexual identity and 13 | orientation. 14 | 15 | We pledge to act and interact in ways that contribute to an open, welcoming, 16 | diverse, inclusive, and healthy community. 17 | 18 | ## Our Standards 19 | 20 | Examples of behavior that contributes to a positive environment for our 21 | community include: 22 | 23 | - Demonstrating empathy and kindness toward other people 24 | - Being respectful of differing opinions, viewpoints, and experiences 25 | - Giving and gracefully accepting constructive feedback 26 | - Accepting responsibility and apologizing to those affected by our mistakes, 27 | and learning from the experience 28 | - Focusing on what is best not just for us as individuals, but for the overall 29 | community 30 | 31 | Examples of unacceptable behavior include: 32 | 33 | - The use of sexualized language or imagery, and sexual attention or advances of 34 | any kind 35 | - Trolling, insulting or derogatory comments, and personal or political attacks 36 | - Public or private harassment 37 | - Publishing others' private information, such as a physical or email address, 38 | without their explicit permission 39 | - Other conduct which could reasonably be considered inappropriate in a 40 | professional setting 41 | 42 | ## Enforcement Responsibilities 43 | 44 | Community leaders are responsible for clarifying and enforcing our standards of 45 | acceptable behavior and will take appropriate and fair corrective action in 46 | response to any behavior that they deem inappropriate, threatening, offensive, 47 | or harmful. 48 | 49 | Community leaders have the right and responsibility to remove, edit, or reject 50 | comments, commits, code, wiki edits, issues, and other contributions that are 51 | not aligned to this Code of Conduct, and will communicate reasons for moderation 52 | decisions when appropriate. 53 | 54 | ## Scope 55 | 56 | This Code of Conduct applies within all community spaces, and also applies when 57 | an individual is officially representing the community in public spaces. 58 | Examples of representing our community include using an official e-mail address, 59 | posting via an official social media account, or acting as an appointed 60 | representative at an online or offline event. 61 | 62 | ## Enforcement 63 | 64 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 65 | reported to the community leaders responsible for enforcement at 66 | ehmicky+report@gmail.com All complaints will be reviewed and investigated 67 | promptly and fairly. 68 | 69 | All community leaders are obligated to respect the privacy and security of the 70 | reporter of any incident. 71 | 72 | ## Enforcement Guidelines 73 | 74 | Community leaders will follow these Community Impact Guidelines in determining 75 | the consequences for any action they deem in violation of this Code of Conduct: 76 | 77 | ### 1. Correction 78 | 79 | **Community Impact**: Use of inappropriate language or other behavior deemed 80 | unprofessional or unwelcome in the community. 81 | 82 | **Consequence**: A private, written warning from community leaders, providing 83 | clarity around the nature of the violation and an explanation of why the 84 | behavior was inappropriate. A public apology may be requested. 85 | 86 | ### 2. Warning 87 | 88 | **Community Impact**: A violation through a single incident or series of 89 | actions. 90 | 91 | **Consequence**: A warning with consequences for continued behavior. No 92 | interaction with the people involved, including unsolicited interaction with 93 | those enforcing the Code of Conduct, for a specified period of time. This 94 | includes avoiding interactions in community spaces as well as external channels 95 | like social media. Violating these terms may lead to a temporary or permanent 96 | ban. 97 | 98 | ### 3. Temporary Ban 99 | 100 | **Community Impact**: A serious violation of community standards, including 101 | sustained inappropriate behavior. 102 | 103 | **Consequence**: A temporary ban from any sort of interaction or public 104 | communication with the community for a specified period of time. No public or 105 | private interaction with the people involved, including unsolicited interaction 106 | with those enforcing the Code of Conduct, is allowed during this period. 107 | Violating these terms may lead to a permanent ban. 108 | 109 | ### 4. Permanent Ban 110 | 111 | **Community Impact**: Demonstrating a pattern of violation of community 112 | standards, including sustained inappropriate behavior, harassment of an 113 | individual, or aggression toward or disparagement of classes of individuals. 114 | 115 | **Consequence**: A permanent ban from any sort of public interaction within the 116 | community. 117 | 118 | ## Attribution 119 | 120 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 121 | version 2.0, available at 122 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 123 | 124 | Community Impact Guidelines were inspired by 125 | [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 126 | 127 | [homepage]: https://www.contributor-covenant.org 128 | 129 | For answers to common questions about this code of conduct, see the FAQ at 130 | https://www.contributor-covenant.org/faq. Translations are available at 131 | https://www.contributor-covenant.org/translations. 132 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributions 2 | 3 | 🎉 Thanks for considering contributing to this project! 🎉 4 | 5 | These guidelines will help you send a pull request. 6 | 7 | If you're submitting an issue instead, please skip this document. 8 | 9 | If your pull request is related to a typo or the documentation being unclear, 10 | please click on the relevant page's `Edit` button (pencil icon) and directly 11 | suggest a correction instead. 12 | 13 | This project was made with ❤️. The simplest way to give back is by starring and 14 | sharing it online. 15 | 16 | Everyone is welcome regardless of personal background. We enforce a 17 | [Code of conduct](CODE_OF_CONDUCT.md) in order to promote a positive and 18 | inclusive environment. 19 | 20 | # Development process 21 | 22 | First fork and clone the repository. If you're not sure how to do this, please 23 | watch 24 | [these videos](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github). 25 | 26 | Run: 27 | 28 | ```bash 29 | npm install 30 | ``` 31 | 32 | Make sure everything is correctly setup with: 33 | 34 | ```bash 35 | npm test 36 | ``` 37 | 38 | We use Gulp tasks to lint, test and build this project. Please check 39 | [dev-tasks](https://github.com/ehmicky/dev-tasks/blob/main/README.md) to learn 40 | how to use them. You don't need to know Gulp to use these tasks. 41 | 42 | # Requirements 43 | 44 | Our coding style is documented 45 | [here](https://github.com/ehmicky/eslint-config#coding-style). Linting and 46 | formatting should automatically handle it though. 47 | 48 | After submitting the pull request, please make sure the Continuous Integration 49 | checks are passing. 50 | 51 | We enforce 100% test coverage: each line of code must be tested. 52 | 53 | New options, methods, properties, configuration and behavior must be documented 54 | in all of these: 55 | 56 | - the `README.md` 57 | - the `docs` directory (if any) 58 | 59 | Please use the same style as the rest of the documentation and examples. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2025 ehmicky 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | wild-wild-utils logo 2 | 3 | [![Node](https://img.shields.io/badge/-Node.js-808080?logo=node.js&colorA=404040&logoColor=66cc33)](https://www.npmjs.com/package/wild-wild-utils) 4 | [![Browsers](https://img.shields.io/badge/-Browsers-808080?logo=firefox&colorA=404040)](https://unpkg.com/wild-wild-utils?module) 5 | [![TypeScript](https://img.shields.io/badge/-Typed-808080?logo=typescript&colorA=404040&logoColor=0096ff)](/src/main.d.ts) 6 | [![Codecov](https://img.shields.io/badge/-Tested%20100%25-808080?logo=codecov&colorA=404040)](https://codecov.io/gh/ehmicky/wild-wild-utils) 7 | [![Minified size](https://img.shields.io/bundlephobia/minzip/wild-wild-utils?label&colorA=404040&colorB=808080&logo=webpack)](https://bundlephobia.com/package/wild-wild-utils) 8 | [![Mastodon](https://img.shields.io/badge/-Mastodon-808080.svg?logo=mastodon&colorA=404040&logoColor=9590F9)](https://fosstodon.org/@ehmicky) 9 | [![Medium](https://img.shields.io/badge/-Medium-808080.svg?logo=medium&colorA=404040)](https://medium.com/@ehmicky) 10 | 11 | 🤠 Functional utilities using object property paths with wildcards and regexps. 12 | 🌵 13 | 14 | Available functional methods include: 15 | 16 | - 🗺️ Mapping: [`map()`](#maptarget-query-mapfunction-options), 17 | [`flatten()`](#flattentarget-options) 18 | - 🚂 Merging/concatenating: [`merge()`](#mergetarget-query-value-options), 19 | [`push()`](#pushtarget-query-values-options), 20 | [`unshift()`](#unshifttarget-query-values-options) 21 | - ⛏️ Finding: [`find()`](#findtarget-query-testfunction-options) 22 | - ⭐ Filtering: [`pick()`](#picktarget-query-options), 23 | [`include()`](#includetarget-query-testfunction-options), 24 | [`exclude()`](#excludetarget-query-testfunction-options) 25 | 26 | Unlike similar libraries, object properties can be get/set using 27 | [dot-delimited paths](https://github.com/ehmicky/wild-wild-path#%EF%B8%8F-deep-properties), 28 | [wildcards](https://github.com/ehmicky/wild-wild-path#-wildcards), 29 | [regexps](https://github.com/ehmicky/wild-wild-path#%EF%B8%8F-regexps), 30 | [slices](https://github.com/ehmicky/wild-wild-path#%EF%B8%8F-array-slices) and 31 | [unions](https://github.com/ehmicky/wild-wild-path#-unions). It is built on top 32 | of [`wild-wild-path`](https://github.com/ehmicky/wild-wild-path). 33 | 34 | # Install 35 | 36 | ```bash 37 | npm install wild-wild-utils 38 | ``` 39 | 40 | This package works in both Node.js >=18.18.0 and 41 | [browsers](https://raw.githubusercontent.com/ehmicky/dev-tasks/main/src/browserslist). 42 | 43 | This is an ES module. It must be loaded using 44 | [an `import` or `import()` statement](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c), 45 | not `require()`. If TypeScript is used, it must be configured to 46 | [output ES modules](https://www.typescriptlang.org/docs/handbook/esm-node.html), 47 | not CommonJS. 48 | 49 | # API 50 | 51 | ## Methods 52 | 53 | ### map(target, query, mapFunction, options?) 54 | 55 | `target`: [`Target`](https://github.com/ehmicky/wild-wild-path#target)\ 56 | `query`: [`Query`](https://github.com/ehmicky/wild-wild-path#queries)\ 57 | `mapFunction`: `(value) => value`\ 58 | `options`: [`Options?`](#options)\ 59 | _Return value_: [`Target`](https://github.com/ehmicky/wild-wild-path#target) 60 | 61 | Use a `mapFunction()` to modify any property matching the `query`. 62 | 63 | ```js 64 | const target = { user: { firstName: 'Alice', lastName: 'Smith' } } 65 | map(target, 'user.*', (userProp) => userProp.toLowerCase()) 66 | // { user: { firstName: 'alice', lastName: 'smith' } } 67 | ``` 68 | 69 | ### merge(target, query, value, options?) 70 | 71 | `target`: [`Target`](https://github.com/ehmicky/wild-wild-path#target)\ 72 | `query`: [`Query`](https://github.com/ehmicky/wild-wild-path#queries)\ 73 | `value`: `any`\ 74 | `options`: [`Options?`](#options)\ 75 | _Return value_: [`Target`](https://github.com/ehmicky/wild-wild-path#target) 76 | 77 | Deeply merge an object `value` with each object property matching the `query`. 78 | 79 | If one of these properties is not an object, it is overridden instead. 80 | 81 | [Any object in `value` can change](https://github.com/ehmicky/declarative-merge#nesting) 82 | the merge mode using a `_merge` property with value 83 | [`"deep"`](https://github.com/ehmicky/declarative-merge#deep-merge) (default), 84 | [`"shallow"`](https://github.com/ehmicky/declarative-merge#shallow-merge), 85 | [`"set"`](https://github.com/ehmicky/declarative-merge#no-merge) or 86 | [`"delete"`](https://github.com/ehmicky/declarative-merge#delete). 87 | 88 | Arrays 89 | [can be merged using objects in `value`](https://github.com/ehmicky/declarative-merge#arrays) 90 | where the keys are the 91 | [array indices](https://github.com/ehmicky/declarative-merge#update). Items can 92 | be [updated](https://github.com/ehmicky/declarative-merge#update), 93 | [merged](https://github.com/ehmicky/declarative-merge#merge), 94 | [added](https://github.com/ehmicky/declarative-merge#add), 95 | [inserted](https://github.com/ehmicky/declarative-merge#insert), 96 | [appended](https://github.com/ehmicky/declarative-merge#append), 97 | [prepended](https://github.com/ehmicky/declarative-merge#prepend) or 98 | [deleted](https://github.com/ehmicky/declarative-merge#delete-1). 99 | 100 | ```js 101 | const target = { 102 | userOne: { names: ['Alice', 'Smith'], settings: { deleted: true } }, 103 | userTwo: { names: ['John', 'Doe'], settings: { deleted: false } }, 104 | } 105 | 106 | merge(target, '*', { age: 72, settings: { admin: true } }) 107 | // { 108 | // userOne: { 109 | // names: ['Alice', 'Smith'], 110 | // settings: { deleted: true, admin: true }, 111 | // age: 72, 112 | // }, 113 | // userTwo: { 114 | // names: ['John', 'Doe'], 115 | // settings: { deleted: false, admin: true }, 116 | // age: 72, 117 | // }, 118 | // } 119 | 120 | merge(target, '*', { age: 72, settings: { admin: true }, _merge: 'shallow' }) 121 | // { 122 | // userOne: { 123 | // names: [ 'Alice', 'Smith' ], 124 | // settings: { admin: true }, 125 | // age: 72, 126 | // }, 127 | // userTwo: { 128 | // names: [ 'John', 'Doe' ], 129 | // settings: { admin: true }, 130 | // age: 72, 131 | // }, 132 | // } 133 | 134 | merge(target, '*', { names: { 1: 'Red' } }) 135 | // { 136 | // userOne: { 137 | // names: ['Alice', 'Red'], 138 | // settings: { deleted: true }, 139 | // age: 72, 140 | // }, 141 | // userTwo: { 142 | // names: ['John', 'Red'], 143 | // settings: { deleted: false }, 144 | // age: 72, 145 | // }, 146 | // } 147 | ``` 148 | 149 | ### push(target, query, values, options?) 150 | 151 | `target`: [`Target`](https://github.com/ehmicky/wild-wild-path#target)\ 152 | `query`: [`Query`](https://github.com/ehmicky/wild-wild-path#queries)\ 153 | `values`: `any[]`\ 154 | `options`: [`Options?`](#options)\ 155 | _Return value_: [`Target`](https://github.com/ehmicky/wild-wild-path#target) 156 | 157 | Concatenate an array of `values` with each array property matching the `query`. 158 | 159 | If one of these properties is not an array, it is overridden instead. 160 | 161 | ```js 162 | const target = { 163 | userOne: { firstName: 'Alice', colors: ['red'] }, 164 | userTwo: { firstName: 'John', colors: ['blue'] }, 165 | } 166 | push(target, '*.colors', ['yellow', 'silver']) 167 | // { 168 | // userOne: { firstName: 'Alice', colors: ['red', 'yellow', 'silver'] }, 169 | // userTwo: { firstName: 'John', colors: ['blue', 'yellow', 'silver'] }, 170 | // } 171 | ``` 172 | 173 | ### unshift(target, query, values, options?) 174 | 175 | `target`: [`Target`](https://github.com/ehmicky/wild-wild-path#target)\ 176 | `query`: [`Query`](https://github.com/ehmicky/wild-wild-path#queries)\ 177 | `values`: `any[]`\ 178 | `options`: [`Options?`](#options)\ 179 | _Return value_: [`Target`](https://github.com/ehmicky/wild-wild-path#target) 180 | 181 | Like [`push()`](#pushtarget-query-values-options) but concatenates at the 182 | beginning of each property instead of at the end. 183 | 184 | ```js 185 | const target = { 186 | userOne: { firstName: 'Alice', colors: ['red'] }, 187 | userTwo: { firstName: 'John', colors: ['blue'] }, 188 | } 189 | unshift(target, '*.colors', ['yellow', 'silver']) 190 | // { 191 | // userOne: { firstName: 'Alice', colors: ['yellow', 'silver', 'red'] }, 192 | // userTwo: { firstName: 'John', colors: ['yellow', 'silver', 'blue'] }, 193 | // } 194 | ``` 195 | 196 | ### find(target, query, testFunction, options?) 197 | 198 | `target`: [`Target`](https://github.com/ehmicky/wild-wild-path#target)\ 199 | `query`: [`Query`](https://github.com/ehmicky/wild-wild-path#queries)\ 200 | `testFunction`: `(value) => boolean`\ 201 | `options`: [`Options?`](#options)\ 202 | _Return value_: `any` 203 | 204 | Return the first property that matches the `query` and that returns `true` with 205 | the `testFunction()`. 206 | 207 | ```js 208 | const target = { 209 | userOne: { firstName: 'Alice', colors: ['red'] }, 210 | userTwo: { firstName: 'John', colors: ['blue'] }, 211 | } 212 | find(target, '*.firstName', (firstName) => firstName !== 'John') // 'Alice' 213 | ``` 214 | 215 | ### pick(target, query, options?) 216 | 217 | `target`: [`Target`](https://github.com/ehmicky/wild-wild-path#target)\ 218 | `query`: [`Query`](https://github.com/ehmicky/wild-wild-path#queries)\ 219 | `options`: [`Options?`](#options)\ 220 | _Return value_: [`Target`](https://github.com/ehmicky/wild-wild-path#target) 221 | 222 | Keep only the properties matching the `query`. 223 | 224 | ```js 225 | const target = { 226 | userOne: { firstName: 'Alice', lastName: 'Smith', age: 72, admin: true }, 227 | userTwo: { firstName: 'John', lastName: 'Doe', age: 72, admin: true }, 228 | } 229 | pick(target, '*./Name/') 230 | // { 231 | // userOne: { firstName: 'Alice', lastName: 'Smith' }, 232 | // userTwo: { firstName: 'John', lastName: 'Doe' }, 233 | // } 234 | ``` 235 | 236 | ### include(target, query, testFunction, options?) 237 | 238 | `target`: [`Target`](https://github.com/ehmicky/wild-wild-path#target)\ 239 | `query`: [`Query`](https://github.com/ehmicky/wild-wild-path#queries)\ 240 | `testFunction`: `(value) => boolean`\ 241 | `options`: [`Options?`](#options)\ 242 | _Return value_: [`Target`](https://github.com/ehmicky/wild-wild-path#target) 243 | 244 | Keep only the properties that match the `query` and that return `true` with the 245 | `testFunction()`. 246 | 247 | ```js 248 | const target = { 249 | userOne: { firstName: 'Alice', lastName: 'Smith', age: 72, admin: true }, 250 | userTwo: { firstName: 'John', lastName: 'Doe', age: 72, admin: true }, 251 | } 252 | include(target, '**', (value) => typeof value === 'string') 253 | // { 254 | // userOne: { firstName: 'Alice', lastName: 'Smith' }, 255 | // userTwo: { firstName: 'John', lastName: 'Doe' }, 256 | // } 257 | ``` 258 | 259 | ### exclude(target, query, testFunction, options?) 260 | 261 | `target`: [`Target`](https://github.com/ehmicky/wild-wild-path#target)\ 262 | `query`: [`Query`](https://github.com/ehmicky/wild-wild-path#queries)\ 263 | `testFunction`: `(value) => boolean`\ 264 | `options`: [`Options?`](#options)\ 265 | _Return value_: [`Target`](https://github.com/ehmicky/wild-wild-path#target) 266 | 267 | Remove any property that matches the `query` and that returns `true` with the 268 | `testFunction()`. 269 | 270 | ```js 271 | const target = { 272 | userOne: { firstName: 'Alice', lastName: 'Smith', age: 72, admin: true }, 273 | userTwo: { firstName: 'John', lastName: 'Doe', age: 72, admin: true }, 274 | } 275 | exclude(target, '**', (value) => typeof value === 'string') 276 | // { 277 | // userOne: { age: 72, admin: true }, 278 | // userTwo: { age: 72, admin: true }, 279 | // } 280 | ``` 281 | 282 | ### flatten(target, options?) 283 | 284 | `target`: [`Target`](https://github.com/ehmicky/wild-wild-path#target)\ 285 | `options`: [`Options?`](#options)\ 286 | _Return value_: [`Target`](https://github.com/ehmicky/wild-wild-path#target) 287 | 288 | Flatten deep properties to shallow properties with 289 | [dot-delimited paths](https://github.com/ehmicky/wild-wild-path#paths). 290 | 291 | ```js 292 | const target = { user: { firstName: 'Bob', colors: ['red', 'blue'] } } 293 | flatten(target) 294 | // { 'user.firstName': 'Bob', 'user.colors.0': 'red', 'user.colors.1': 'blue' } 295 | ``` 296 | 297 | ## Target 298 | 299 | The target value must be an object or an array. 300 | 301 | ## Query 302 | 303 | The query format is documented 304 | [here](https://github.com/ehmicky/wild-wild-path#queries). Both query 305 | [strings](https://github.com/ehmicky/wild-wild-path#query-strings) and 306 | [arrays](https://github.com/ehmicky/wild-wild-path#query-arrays) can be used. 307 | 308 | ## Options 309 | 310 | Options are optional plain objects. They are almost 311 | [the same as in `wild-wild-path`](https://github.com/ehmicky/wild-wild-path#options). 312 | 313 | ### mutate 314 | 315 | _Methods_: [`map()`](#maptarget-query-mapfunction-options), 316 | [`merge()`](#mergetarget-query-value-options), 317 | [`push()`](#pushtarget-query-values-options), 318 | [`unshift()`](#unshifttarget-query-values-options), 319 | [`exclude()`](#excludetarget-query-testfunction-options)\ 320 | _Type_: `boolean`\ 321 | _Default_: `false` 322 | 323 | By default, the [target](https://github.com/ehmicky/wild-wild-path#target) is 324 | deeply cloned.\ 325 | When `true`, it is directly mutated instead, which is faster but has side 326 | effects. 327 | 328 | ```js 329 | const target = { colors: ['red'] } 330 | console.log(push(target, 'colors', ['blue'])) 331 | // { colors: ['red', 'blue'] } 332 | console.log(target) 333 | // { colors: ['red'] } 334 | console.log(push(target, 'colors', ['blue'], { mutate: true })) 335 | // { colors: ['red', 'blue'] } 336 | console.log(target) 337 | // { colors: ['red', 'blue'] } 338 | ``` 339 | 340 | ### entries 341 | 342 | _Methods_: [`map()`](#maptarget-query-mapfunction-options), 343 | [`find()`](#findtarget-query-testfunction-options), 344 | [`include()`](#includetarget-query-testfunction-options), 345 | [`exclude()`](#excludetarget-query-testfunction-options)\ 346 | _Type_: `boolean`\ 347 | _Default_: `false` 348 | 349 | By default, properties' values are: 350 | 351 | - Passed as argument to callbacks like `mapFunction()` and `testFunction()` 352 | - Returned by [`find()`](#findtarget-query-testfunction-options) 353 | 354 | When `true`, objects with the following shape are used instead: 355 | 356 | - `value` `any`: property's value 357 | - `path` [`Path`](https://github.com/ehmicky/wild-wild-path#paths): property's 358 | full path 359 | - `missing` `boolean`: whether the property is [missing](#missing) from the 360 | [target](https://github.com/ehmicky/wild-wild-path#target) 361 | 362 | ```js 363 | const target = { job: '', firstName: 'Alice', lastName: 'Smith' } 364 | find(target, '*', (value) => value !== '') // 'Alice' 365 | find( 366 | target, 367 | '*', 368 | (entry) => entry.value !== '' && entry.path[0] !== 'firstName', 369 | { entries: true }, 370 | ) 371 | // { value: 'Smith', path: ['lastName'], missing: false }, 372 | ``` 373 | 374 | ### missing 375 | 376 | _Methods_: [`map()`](#maptarget-query-mapfunction-options), 377 | [`merge()`](#mergetarget-query-value-options), 378 | [`push()`](#pushtarget-query-values-options), 379 | [`unshift()`](#unshifttarget-query-values-options)\ 380 | _Type_: `boolean`\ 381 | _Default_: `false` with `map()`, `true` with `merge|push|unshift()` 382 | 383 | When `false`, properties 384 | [not defined in the target](https://github.com/ehmicky/wild-wild-path#undefined-values) 385 | are ignored. 386 | 387 | ```js 388 | const target = {} 389 | 390 | push(target, 'colors', ['red']) // { colors: ['red'] } 391 | push(target, 'colors', ['red'], { missing: false }) // {} 392 | 393 | map(target, 'name', (value = 'defaultName') => value) // {} 394 | map(target, 'name', ({ value = 'defaultName' }) => value, { 395 | missing: true, 396 | entries: true, 397 | }) // { name: 'defaultName' } 398 | ``` 399 | 400 | ### sort 401 | 402 | _Methods_: [`find()`](#findtarget-query-testfunction-options), 403 | [`pick()`](#picktarget-query-options), 404 | [`include()`](#includetarget-query-testfunction-options),\ 405 | [`flatten()`](#flattentarget-options)\ 406 | _Type_: `boolean`\ 407 | _Default_: `false` 408 | 409 | When returning sibling object properties, sort them by the lexigographic order 410 | of their names (not values). 411 | 412 | ```js 413 | const target = { user: { lastName: 'Doe', firstName: 'John', age: 72 } } 414 | flatten(target) 415 | // { 'user.lastName': 'Doe', 'user.firstName': 'John', 'user.age': 72 } 416 | flatten(target, { sort: true }) 417 | // { 'user.age': 72, 'user.firstName': 'John', 'user.lastName': 'Doe' } 418 | ``` 419 | 420 | ### childFirst 421 | 422 | _Methods_: [`find()`](#findtarget-query-testfunction-options)\ 423 | _Type_: `boolean`\ 424 | _Default_: `false` 425 | 426 | When using [unions](https://github.com/ehmicky/wild-wild-path#-unions) or 427 | [deep wildcards](https://github.com/ehmicky/wild-wild-path#-wildcards), a query 428 | might match both a property and some of its children. 429 | 430 | This option decides whether the returned properties should be sorted from 431 | children to parents, or the reverse. 432 | 433 | ```js 434 | const target = { user: { firstName: 'Alice', lastName: '' } } 435 | const isDefined = (value) => value !== '' 436 | find(target, 'user.**', isDefined) // { firstName: 'Alice', lastName: '' } 437 | find(target, 'user.**', isDefined, { childFirst: true }) // 'Alice' 438 | ``` 439 | 440 | ### leaves 441 | 442 | _Methods_: [`map()`](#maptarget-query-mapfunction-options), 443 | [`merge()`](#mergetarget-query-value-options), 444 | [`push()`](#pushtarget-query-values-options), 445 | [`unshift()`](#unshifttarget-query-values-options), 446 | [`find()`](#findtarget-query-testfunction-options)\ 447 | _Type_: `boolean`\ 448 | _Default_: `false` 449 | 450 | When using [unions](https://github.com/ehmicky/wild-wild-path#-unions) or 451 | [deep wildcards](https://github.com/ehmicky/wild-wild-path#-wildcards), a query 452 | might match both a property and some of its children. 453 | 454 | When `true`, only leaves are matched. In other words, a matching property is 455 | ignored if one of its children also matches. 456 | 457 | ```js 458 | const target = { user: { settings: { firstName: 'Alice', lastName: 'Smith' } } } 459 | merge(target, 'user user.settings', { age: 72 }) 460 | // { 461 | // user: { 462 | // settings: { firstName: 'Alice', lastName: 'Smith', age: 72 }, 463 | // age: 72, 464 | // } 465 | // } 466 | merge(target, 'user user.settings', { age: 72 }, { leaves: true }) 467 | // { 468 | // user: { 469 | // settings: { firstName: 'Alice', lastName: 'Smith', age: 72 }, 470 | // } 471 | // } 472 | ``` 473 | 474 | ### roots 475 | 476 | _Methods_: [`map()`](#maptarget-query-mapfunction-options), 477 | [`merge()`](#mergetarget-query-value-options), 478 | [`push()`](#pushtarget-query-values-options), 479 | [`unshift()`](#unshifttarget-query-values-options), 480 | [`find()`](#findtarget-query-testfunction-options)\ 481 | _Type_: `boolean`\ 482 | _Default_: `false` 483 | 484 | When using [unions](https://github.com/ehmicky/wild-wild-path#-unions) or 485 | [deep wildcards](https://github.com/ehmicky/wild-wild-path#-wildcards), a query 486 | might match both a property and some of its children. 487 | 488 | When `true`, only roots are matched. In other words, a matching property is 489 | ignored if one of its parents also matches. 490 | 491 | ```js 492 | const target = { user: { settings: { firstName: 'Alice', lastName: 'Smith' } } } 493 | merge(target, 'user user.settings', { age: 72 }) 494 | // { 495 | // user: { 496 | // settings: { firstName: 'Alice', lastName: 'Smith', age: 72 }, 497 | // age: 72, 498 | // } 499 | // } 500 | merge(target, 'user user.settings', { age: 72 }, { roots: true }) 501 | // { 502 | // user: { 503 | // settings: { firstName: 'Alice', lastName: 'Smith' }, 504 | // age: 72, 505 | // } 506 | // } 507 | ``` 508 | 509 | ### shallowArrays 510 | 511 | _Methods_: all\ 512 | _Type_: `boolean`\ 513 | _Default_: `false` 514 | 515 | If `true`, [wildcards](https://github.com/ehmicky/wild-wild-path#-wildcards) do 516 | not recurse on arrays. Array items can still be matched by using 517 | [indices](https://github.com/ehmicky/wild-wild-path#-arrays-indices) or 518 | [slices](https://github.com/ehmicky/wild-wild-path#%EF%B8%8F-array-slices). 519 | 520 | ```js 521 | const target = { user: { firstName: 'Bob', colors: ['red', 'blue'] } } 522 | flatten(target) 523 | // { 'user.firstName': 'Bob', 'user.colors.0': 'red', 'user.colors.1': 'blue' } 524 | flatten(target, { shallowArrays: true }) 525 | // { 'user.firstName': 'Bob', 'user.colors': ['red', 'blue'] } 526 | ``` 527 | 528 | ### classes 529 | 530 | _Methods_: all\ 531 | _Type_: `boolean`\ 532 | _Default_: `false` 533 | 534 | Unless `true`, [wildcards](https://github.com/ehmicky/wild-wild-path#-wildcards) 535 | and [regexps](https://github.com/ehmicky/wild-wild-path#%EF%B8%8F-regexps) 536 | ignore properties of objects that are not plain objects (like class instances, 537 | errors or functions). Those can still be matched by using their 538 | [property name](https://github.com/ehmicky/wild-wild-path#%EF%B8%8F-deep-properties). 539 | 540 | ```js 541 | const target = { user: new User({ name: 'Alice' }) } 542 | const isDefined = (value) => value !== '' 543 | find(target, 'user.*', isDefined) // undefined 544 | find(target, 'user.*', isDefined, { classes: true }) // 'Alice' 545 | ``` 546 | 547 | ### inherited 548 | 549 | _Methods_: all\ 550 | _Type_: `boolean`\ 551 | _Default_: `false` 552 | 553 | By default, [wildcards](https://github.com/ehmicky/wild-wild-path#-wildcards) 554 | and [regexps](https://github.com/ehmicky/wild-wild-path#%EF%B8%8F-regexps) 555 | ignore properties that are either 556 | [inherited](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) 557 | or 558 | [not enumerable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties). 559 | Those can still be matched by using their 560 | [property name](https://github.com/ehmicky/wild-wild-path#%EF%B8%8F-deep-properties). 561 | 562 | When `true`, inherited properties are not ignored, but not enumerable ones still 563 | are. 564 | 565 | # Related projects 566 | 567 | - [`wild-wild-path`](https://github.com/ehmicky/wild-wild-path): object property 568 | paths used by `wild-wild-utils` 569 | - [`wild-wild-parser`](https://github.com/ehmicky/wild-wild-parser): parser for 570 | `wild-wild-path`'s object property paths 571 | - [`declarative-merge`](https://github.com/ehmicky/declarative-merge): object 572 | merging logic used by the [`merge()` method](#mergetarget-query-value-options) 573 | - [`set-array`](https://github.com/ehmicky/set-array): array update logic used 574 | by the [`merge()` method](#mergetarget-query-value-options) 575 | 576 | # Support 577 | 578 | For any question, _don't hesitate_ to [submit an issue on GitHub](../../issues). 579 | 580 | Everyone is welcome regardless of personal background. We enforce a 581 | [Code of conduct](CODE_OF_CONDUCT.md) in order to promote a positive and 582 | inclusive environment. 583 | 584 | # Contributing 585 | 586 | This project was made with ❤️. The simplest way to give back is by starring and 587 | sharing it online. 588 | 589 | If the documentation is unclear or has a typo, please click on the page's `Edit` 590 | button (pencil icon) and suggest a correction. 591 | 592 | If you would like to help us fix a bug or add a new feature, please check our 593 | [guidelines](CONTRIBUTING.md). Pull requests are welcome! 594 | 595 | 596 | 597 | 598 | 599 | 602 | 603 | -------------------------------------------------------------------------------- /ava.config.js: -------------------------------------------------------------------------------- 1 | export { default } from '@ehmicky/dev-tasks/ava.config.js' 2 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | export { default } from '@ehmicky/eslint-config' 2 | -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | export * from '@ehmicky/dev-tasks' 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wild-wild-utils", 3 | "version": "6.0.1", 4 | "type": "module", 5 | "exports": { 6 | "types": "./build/src/main.d.ts", 7 | "default": "./build/src/main.js" 8 | }, 9 | "main": "./build/src/main.js", 10 | "types": "./build/src/main.d.ts", 11 | "files": [ 12 | "build/src/**/*.{js,json,d.ts}", 13 | "!build/src/**/*.test.js", 14 | "!build/src/{helpers,fixtures}" 15 | ], 16 | "sideEffects": false, 17 | "scripts": { 18 | "test": "gulp test" 19 | }, 20 | "description": "🤠 Functional utilities using object property paths with wildcards and regexps 🌵", 21 | "keywords": [ 22 | "wildcard", 23 | "glob", 24 | "globbing", 25 | "globstar", 26 | "regex", 27 | "regexp", 28 | "regular-expression", 29 | "path", 30 | "recursion", 31 | "functional-programming", 32 | "map", 33 | "filter", 34 | "algorithm", 35 | "data-structures", 36 | "javascript", 37 | "json", 38 | "library", 39 | "nodejs", 40 | "parsing", 41 | "typescript" 42 | ], 43 | "license": "Apache-2.0", 44 | "homepage": "https://www.github.com/ehmicky/wild-wild-utils", 45 | "repository": { 46 | "type": "git", 47 | "url": "git+https://github.com/ehmicky/wild-wild-utils.git" 48 | }, 49 | "bugs": { 50 | "url": "https://github.com/ehmicky/wild-wild-utils/issues" 51 | }, 52 | "author": "ehmicky (https://github.com/ehmicky)", 53 | "directories": { 54 | "lib": "src" 55 | }, 56 | "dependencies": { 57 | "declarative-merge": "^4.0.1", 58 | "wild-wild-parser": "^5.0.1", 59 | "wild-wild-path": "^5.0.1" 60 | }, 61 | "devDependencies": { 62 | "@ehmicky/dev-tasks": "^3.0.34", 63 | "@ehmicky/eslint-config": "^20.0.32", 64 | "@ehmicky/prettier-config": "^1.0.6", 65 | "test-each": "^7.0.1" 66 | }, 67 | "engines": { 68 | "node": ">=18.18.0" 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | export { default } from '@ehmicky/prettier-config' 2 | -------------------------------------------------------------------------------- /src/find.js: -------------------------------------------------------------------------------- 1 | import { iterate } from 'wild-wild-path' 2 | 3 | import { validateFunction } from './validate.js' 4 | 5 | // Find the first non-missing property that matches a condition 6 | export const find = ( 7 | target, 8 | query, 9 | condition, 10 | { 11 | childFirst, 12 | roots, 13 | leaves, 14 | sort, 15 | entries, 16 | shallowArrays, 17 | classes, 18 | inherited, 19 | } = {}, 20 | // eslint-disable-next-line max-params 21 | ) => { 22 | validateFunction(condition) 23 | 24 | // eslint-disable-next-line fp/no-loops 25 | for (const entry of iterate(target, query, { 26 | childFirst, 27 | roots, 28 | leaves, 29 | sort, 30 | missing: false, 31 | entries, 32 | shallowArrays, 33 | classes, 34 | inherited, 35 | })) { 36 | // eslint-disable-next-line max-depth 37 | if (condition(entry)) { 38 | return entry 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/find.test.js: -------------------------------------------------------------------------------- 1 | import { isOne, returnTrue } from './helpers/functions.test.js' 2 | import { getChild } from './helpers/inherited.test.js' 3 | import { testOutput } from './helpers/output.test.js' 4 | import { testValidation } from './helpers/validate.test.js' 5 | 6 | import { find } from 'wild-wild-utils' 7 | 8 | const child = getChild() 9 | 10 | testOutput('find', find, [ 11 | // Main usage 12 | { input: [{ two: 2, one: 1 }, '*', isOne], output: 1 }, 13 | { input: [{ two: 2, one: 1 }, '*', returnTrue], output: 2 }, 14 | { input: [{}, 'one', returnTrue], output: undefined }, 15 | 16 | // `childFirst`, `leaves` and `roots` options 17 | { input: [{ one: 1 }, '**', returnTrue], output: { one: 1 } }, 18 | { input: [{ one: 1 }, '**', returnTrue, { childFirst: true }], output: 1 }, 19 | { input: [{ one: 1 }, '**', returnTrue, { leaves: true }], output: 1 }, 20 | { 21 | input: [{ one: 1 }, '**', returnTrue, { childFirst: true, roots: true }], 22 | output: { one: 1 }, 23 | }, 24 | 25 | // `sort` option 26 | { input: [{ two: 2, one: 1 }, '*', returnTrue], output: 2 }, 27 | { input: [{ two: 2, one: 1 }, '*', returnTrue, { sort: true }], output: 1 }, 28 | 29 | // `entries` option 30 | { 31 | input: [{ one: 1 }, '*', returnTrue, { entries: true }], 32 | output: { value: 1, path: ['one'], missing: false }, 33 | }, 34 | { input: [{}, 'one', returnTrue, { entries: true }], output: undefined }, 35 | 36 | // `shallowArrays` option 37 | { input: [[1], '*', returnTrue], output: 1 }, 38 | { input: [[1], '*', returnTrue, { shallowArrays: true }], output: undefined }, 39 | 40 | // `classes` and `inherited` options 41 | { input: [child, '/own/', returnTrue], output: undefined }, 42 | { input: [child, '/own/', returnTrue, { classes: true }], output: 'own' }, 43 | { input: [child, '/inherited/', returnTrue], output: undefined }, 44 | { 45 | input: [child, '/inherited/', returnTrue, { classes: true }], 46 | output: undefined, 47 | }, 48 | { 49 | input: [ 50 | child, 51 | '/inherited/', 52 | returnTrue, 53 | { classes: true, inherited: true }, 54 | ], 55 | output: 'inherited', 56 | }, 57 | ]) 58 | 59 | testValidation('find', find, [ 60 | [{}, true, returnTrue], 61 | [{}, '.', true], 62 | ]) 63 | -------------------------------------------------------------------------------- /src/flatten.js: -------------------------------------------------------------------------------- 1 | import { serializePath } from 'wild-wild-parser' 2 | import { list } from 'wild-wild-path' 3 | 4 | // Flattens all deep properties into a shallow object where each key is a path 5 | export const flatten = ( 6 | target, 7 | { sort, shallowArrays, classes, inherited } = {}, 8 | ) => { 9 | const entries = list(target, '**', { 10 | childFirst: false, 11 | roots: false, 12 | leaves: true, 13 | sort, 14 | missing: false, 15 | entries: true, 16 | shallowArrays, 17 | classes, 18 | inherited, 19 | }) 20 | return Object.fromEntries(entries.map(flattenEntry)) 21 | } 22 | 23 | const flattenEntry = ({ path, value }) => [serializePath(path), value] 24 | -------------------------------------------------------------------------------- /src/flatten.test.js: -------------------------------------------------------------------------------- 1 | import { getChild } from './helpers/inherited.test.js' 2 | import { testOutput } from './helpers/output.test.js' 3 | 4 | import { flatten } from 'wild-wild-utils' 5 | 6 | testOutput('flatten', flatten, [ 7 | // Main usage 8 | { 9 | input: [{ one: { two: 2 }, three: 3 }], 10 | output: { 'one.two': 2, three: 3 }, 11 | }, 12 | { input: [[1, { one: 1 }]], output: { 0: 1, '1.one': 1 } }, 13 | 14 | // `shallowArrays` option 15 | { 16 | input: [{ one: { two: [{ three: 3 }] } }], 17 | output: { 'one.two.0.three': 3 }, 18 | }, 19 | { 20 | input: [{ one: { two: [{ three: 3 }] } }, { shallowArrays: true }], 21 | output: { 'one.two': [{ three: 3 }] }, 22 | }, 23 | 24 | // `classes` and `inherited` options 25 | { input: [getChild({ own: 1 })], output: { '.': getChild({ own: 1 }) } }, 26 | { input: [getChild({ own: 1 }), { classes: true }], output: { own: 1 } }, 27 | { 28 | input: [getChild({ own: 1 }), { classes: true, inherited: true }], 29 | output: { inherited: 'inherited', own: 1 }, 30 | }, 31 | ]) 32 | -------------------------------------------------------------------------------- /src/helpers/functions.test.js: -------------------------------------------------------------------------------- 1 | // Functions used as test helpers 2 | export const returnFalse = () => false 3 | 4 | export const returnTrue = () => true 5 | 6 | export const isOne = (value) => value === 1 7 | 8 | export const isNotOne = (value) => value !== 1 9 | 10 | export const isObject = (value) => typeof value === 'object' 11 | 12 | export const isNotObject = (value) => typeof value !== 'object' 13 | 14 | export const isNamedTwo = ({ path }) => path[0] === 'two' 15 | 16 | export const identity = (value) => value 17 | -------------------------------------------------------------------------------- /src/helpers/inherited.test.js: -------------------------------------------------------------------------------- 1 | // Retrieve class instances with both own and inherited properties 2 | /* eslint-disable fp/no-class, fp/no-this, fp/no-mutation */ 3 | export const getChild = (opts = {}) => { 4 | class Parent {} 5 | Parent.prototype.inherited = 'inherited' 6 | 7 | class Child extends Parent { 8 | constructor() { 9 | super() 10 | 11 | if (!('own' in opts)) { 12 | this.own = 'own' 13 | } else if (opts.own !== undefined) { 14 | this.own = opts.own 15 | } 16 | 17 | if ('inherited' in opts) { 18 | this.inherited = opts.inherited 19 | } 20 | } 21 | } 22 | return new Child() 23 | } 24 | /* eslint-enable fp/no-class, fp/no-this, fp/no-mutation */ 25 | -------------------------------------------------------------------------------- /src/helpers/mutate.test.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line ava/no-ignored-test-files 2 | import test from 'ava' 3 | import { each } from 'test-each' 4 | 5 | // Test multiple inputs with the `mutate` option either `true` or `false` 6 | export const testMutate = (name, method, inputs) => { 7 | each([false, true], inputs, ({ title }, mutate, { input, opts, output }) => 8 | testMutateSingle({ title, name, method, mutate, input, opts, output }), 9 | ) 10 | } 11 | 12 | const testMutateSingle = ({ 13 | title, 14 | name, 15 | method, 16 | mutate, 17 | input, 18 | input: [target], 19 | opts = {}, 20 | output, 21 | }) => { 22 | if (opts.mutate && !mutate) { 23 | return 24 | } 25 | 26 | test(`${name}() output | ${title}`, (t) => { 27 | t.deepEqual(method(...input, { mutate, ...opts }), output) 28 | 29 | if (mutate) { 30 | t.deepEqual(target, output) 31 | } 32 | }) 33 | } 34 | -------------------------------------------------------------------------------- /src/helpers/output.test.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line ava/no-ignored-test-files 2 | import test from 'ava' 3 | import { each } from 'test-each' 4 | 5 | // Test the output of a specific method based on its input 6 | export const testOutput = (name, method, inputs) => { 7 | each(inputs, ({ title }, { input, output }) => 8 | testOutputSingle({ name, method, title, input, output }), 9 | ) 10 | } 11 | 12 | const testOutputSingle = ({ title, name, method, input, output }) => { 13 | test(`${name}() output | ${title}`, (t) => { 14 | t.deepEqual(method(...input), output) 15 | }) 16 | } 17 | -------------------------------------------------------------------------------- /src/helpers/validate.test.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line ava/no-ignored-test-files 2 | import test from 'ava' 3 | import { each } from 'test-each' 4 | 5 | // Test that a given method throws on invalid input 6 | export const testValidation = (name, method, inputs) => { 7 | each(inputs, ({ title }, input) => 8 | testValidationSingle({ name, method, title, input }), 9 | ) 10 | } 11 | 12 | const testValidationSingle = ({ name, method, title, input }) => { 13 | test(`${name}() validates its input | ${title}`, (t) => { 14 | t.throws(method.bind(undefined, ...input)) 15 | }) 16 | } 17 | -------------------------------------------------------------------------------- /src/include/exclude.js: -------------------------------------------------------------------------------- 1 | import { remove } from 'wild-wild-path' 2 | 3 | import { validateFunction } from '../validate.js' 4 | 5 | import { reduceParents } from './reduce.js' 6 | 7 | // Remove values matching a query 8 | export const exclude = ( 9 | target, 10 | query, 11 | condition, 12 | { mutate, entries, shallowArrays, classes, inherited } = {}, 13 | // eslint-disable-next-line max-params 14 | ) => { 15 | validateFunction(condition) 16 | const setFunc = excludeEntry.bind(undefined, { 17 | mutate, 18 | shallowArrays, 19 | classes, 20 | inherited, 21 | }) 22 | return reduceParents({ 23 | setFunc, 24 | condition, 25 | target, 26 | newTarget: target, 27 | query, 28 | roots: false, 29 | sort: false, 30 | entries, 31 | shallowArrays, 32 | classes, 33 | inherited, 34 | }) 35 | } 36 | 37 | const excludeEntry = ( 38 | { mutate, shallowArrays, classes, inherited }, 39 | newTarget, 40 | { path }, 41 | ) => remove(newTarget, path, { mutate, shallowArrays, classes, inherited }) 42 | -------------------------------------------------------------------------------- /src/include/exclude.test.js: -------------------------------------------------------------------------------- 1 | import { 2 | isNamedTwo, 3 | isNotOne, 4 | isOne, 5 | returnFalse, 6 | returnTrue, 7 | } from '../helpers/functions.test.js' 8 | import { getChild } from '../helpers/inherited.test.js' 9 | import { testMutate } from '../helpers/mutate.test.js' 10 | import { testValidation } from '../helpers/validate.test.js' 11 | 12 | import { exclude } from 'wild-wild-utils' 13 | 14 | testMutate('exclude', exclude, [ 15 | // Main usage 16 | { 17 | input: [{ one: 1, two: 2 }, 'one', returnFalse], 18 | output: { one: 1, two: 2 }, 19 | }, 20 | { input: [{ one: 1, two: 2 }, 'one', returnTrue], output: { two: 2 } }, 21 | { input: [{ two: 2 }, 'one', returnFalse], output: { two: 2 } }, 22 | { input: [{ one: { two: 2 } }, 'one one.two', returnTrue], output: {} }, 23 | { input: [{ one: { two: 1 } }, 'one one.two', isOne], output: { one: {} } }, 24 | { input: [{ one: { two: 1 } }, 'one one.two', isNotOne], output: {} }, 25 | 26 | // `entries` option 27 | { 28 | input: [{ one: 1, two: 2 }, 'one two', isNamedTwo], 29 | opts: { entries: true }, 30 | output: { one: 1 }, 31 | }, 32 | 33 | // `shallowArrays` option 34 | { input: [{ one: [1] }, 'one.*', returnTrue], output: { one: [] } }, 35 | { 36 | input: [{ one: [1] }, 'one.*', returnTrue, { shallowArrays: true }], 37 | output: { one: [1] }, 38 | }, 39 | 40 | // `classes` and `inherited` options 41 | { input: [getChild(), '/own/', returnTrue], output: getChild() }, 42 | { 43 | input: [getChild(), '/own/', returnTrue], 44 | opts: { classes: true, mutate: true }, 45 | output: getChild({ own: undefined }), 46 | }, 47 | { input: [getChild(), '/inherited/', returnTrue], output: getChild() }, 48 | { 49 | input: [getChild(), '/inherited/', returnTrue], 50 | opts: { classes: true, mutate: true }, 51 | output: getChild(), 52 | }, 53 | { 54 | input: [getChild(), '/inherited/', returnTrue], 55 | opts: { classes: true, inherited: true, mutate: true }, 56 | output: getChild({ inherited: undefined }), 57 | }, 58 | ]) 59 | 60 | testValidation('exclude', exclude, [ 61 | [{}, true, returnFalse], 62 | [{}, '.', true], 63 | ]) 64 | -------------------------------------------------------------------------------- /src/include/include.js: -------------------------------------------------------------------------------- 1 | import { validateFunction } from '../validate.js' 2 | 3 | import { pickEntry } from './pick.js' 4 | import { reduceParents } from './reduce.js' 5 | 6 | // Remove values not matching a query 7 | export const include = ( 8 | target, 9 | query, 10 | condition, 11 | { sort, entries, shallowArrays, classes, inherited } = {}, 12 | // eslint-disable-next-line max-params 13 | ) => { 14 | validateFunction(condition) 15 | const setFunc = pickEntry.bind(undefined, { 16 | shallowArrays, 17 | classes, 18 | inherited, 19 | }) 20 | return reduceParents({ 21 | setFunc, 22 | condition, 23 | target, 24 | newTarget: {}, 25 | query, 26 | roots: false, 27 | sort, 28 | entries, 29 | shallowArrays, 30 | classes, 31 | inherited, 32 | }) 33 | } 34 | -------------------------------------------------------------------------------- /src/include/include.test.js: -------------------------------------------------------------------------------- 1 | import { 2 | isNamedTwo, 3 | isNotObject, 4 | isObject, 5 | isOne, 6 | returnFalse, 7 | returnTrue, 8 | } from '../helpers/functions.test.js' 9 | import { getChild } from '../helpers/inherited.test.js' 10 | import { testOutput } from '../helpers/output.test.js' 11 | import { testValidation } from '../helpers/validate.test.js' 12 | 13 | import { include } from 'wild-wild-utils' 14 | 15 | const child = getChild() 16 | 17 | testOutput('include', include, [ 18 | // Main usage 19 | { 20 | input: [{ one: 1, two: 2 }, 'one two', returnTrue], 21 | output: { one: 1, two: 2 }, 22 | }, 23 | { input: [{ one: 1, two: 2 }, 'one two', returnFalse], output: {} }, 24 | { input: [{ one: 1, two: 2 }, 'one', returnTrue], output: { one: 1 } }, 25 | { input: [{ one: 1, two: 2 }, 'one two', isOne], output: { one: 1 } }, 26 | { input: [{ one: 1 }, 'two', returnTrue], output: {} }, 27 | { input: [{ one: { two: 2 } }, 'one one.two', returnFalse], output: {} }, 28 | { 29 | input: [{ one: { two: 2, three: 3 } }, 'one one.two', isObject], 30 | output: { one: { two: 2, three: 3 } }, 31 | }, 32 | { 33 | input: [{ one: { two: 2, three: 3 } }, 'one one.two', isNotObject], 34 | output: { one: { two: 2 } }, 35 | }, 36 | 37 | // `entries` option 38 | { 39 | input: [{ one: 1, two: 2 }, 'one two', isNamedTwo, { entries: true }], 40 | output: { two: 2 }, 41 | }, 42 | 43 | // `sort` option 44 | { 45 | input: [{ two: 2, one: 1 }, 'one two', returnTrue], 46 | output: { two: 2, one: 1 }, 47 | }, 48 | { 49 | input: [{ two: 2, one: 1 }, 'one two', returnTrue, { sort: true }], 50 | output: { one: 1, two: 2 }, 51 | }, 52 | 53 | // `shallowArrays` option 54 | { input: [{ one: [1] }, 'one.*', returnTrue], output: { one: [1] } }, 55 | { 56 | input: [{ one: [1] }, 'one.*', returnTrue, { shallowArrays: true }], 57 | output: {}, 58 | }, 59 | 60 | // `classes` and `inherited` options 61 | { input: [child, '/own/', returnTrue], output: {} }, 62 | { 63 | input: [child, '/own/', returnTrue, { classes: true }], 64 | output: { own: 'own' }, 65 | }, 66 | { input: [child, '/inherited/', returnTrue], output: {} }, 67 | { input: [child, '/inherited/', returnTrue, { classes: true }], output: {} }, 68 | { 69 | input: [ 70 | child, 71 | '/inherited/', 72 | returnTrue, 73 | { classes: true, inherited: true }, 74 | ], 75 | output: { inherited: 'inherited' }, 76 | }, 77 | ]) 78 | 79 | testValidation('include', include, [ 80 | [{}, true, returnTrue], 81 | [{}, '.', true], 82 | ]) 83 | -------------------------------------------------------------------------------- /src/include/pick.js: -------------------------------------------------------------------------------- 1 | import { set } from 'wild-wild-path' 2 | 3 | import { reduceParents } from './reduce.js' 4 | 5 | // Returns an object with only the properties being queried. 6 | export const pick = ( 7 | target, 8 | query, 9 | { sort, shallowArrays, classes, inherited } = {}, 10 | ) => { 11 | const setFunc = pickEntry.bind(undefined, { 12 | shallowArrays, 13 | classes, 14 | inherited, 15 | }) 16 | return reduceParents({ 17 | setFunc, 18 | target, 19 | newTarget: {}, 20 | query, 21 | roots: true, 22 | sort, 23 | shallowArrays, 24 | classes, 25 | inherited, 26 | }) 27 | } 28 | 29 | export const pickEntry = ( 30 | { shallowArrays, classes, inherited }, 31 | newTarget, 32 | { path, value }, 33 | ) => 34 | set(newTarget, path, value, { 35 | mutate: true, 36 | shallowArrays, 37 | classes, 38 | inherited, 39 | }) 40 | -------------------------------------------------------------------------------- /src/include/pick.test.js: -------------------------------------------------------------------------------- 1 | import { getChild } from '../helpers/inherited.test.js' 2 | import { testOutput } from '../helpers/output.test.js' 3 | import { testValidation } from '../helpers/validate.test.js' 4 | 5 | import { pick } from 'wild-wild-utils' 6 | 7 | const child = getChild() 8 | 9 | testOutput('pick', pick, [ 10 | // Main usage 11 | { input: [{ one: 1, two: 2 }, 'one two'], output: { one: 1, two: 2 } }, 12 | { input: [{ one: 1, two: 2 }, 'one'], output: { one: 1 } }, 13 | { input: [{ one: 1 }, 'two'], output: {} }, 14 | { input: [{ one: { two: 2 } }, 'one one.two'], output: { one: { two: 2 } } }, 15 | { 16 | input: [{ one: { two: 2, three: 3 } }, 'one one.two'], 17 | output: { one: { two: 2, three: 3 } }, 18 | }, 19 | 20 | // `shallowArrays` option 21 | { input: [{ one: [1] }, 'one.*'], output: { one: [1] } }, 22 | { input: [{ one: [1] }, 'one.*', { shallowArrays: true }], output: {} }, 23 | 24 | // `sort` option 25 | { input: [{ two: 2, one: 1 }, 'one two'], output: { two: 2, one: 1 } }, 26 | { 27 | input: [{ two: 2, one: 1 }, 'one two', { sort: true }], 28 | output: { one: 1, two: 2 }, 29 | }, 30 | 31 | // `classes` and `inherited` options 32 | { input: [child, '/own/'], output: {} }, 33 | { input: [child, '/own/', { classes: true }], output: { own: 'own' } }, 34 | { input: [child, '/inherited/'], output: {} }, 35 | { input: [child, '/inherited/', { classes: true }], output: {} }, 36 | { 37 | input: [child, '/inherited/', { classes: true, inherited: true }], 38 | output: { inherited: 'inherited' }, 39 | }, 40 | ]) 41 | 42 | testValidation('pick', pick, [[{}, true]]) 43 | -------------------------------------------------------------------------------- /src/include/reduce.js: -------------------------------------------------------------------------------- 1 | import { isParentPath } from 'wild-wild-parser' 2 | import { list } from 'wild-wild-path' 3 | 4 | // Modify a target object multiple times for each matched property. 5 | export const reduceParents = ({ 6 | setFunc, 7 | condition, 8 | target, 9 | newTarget, 10 | query, 11 | sort, 12 | roots, 13 | entries: entriesOpt, 14 | shallowArrays, 15 | classes, 16 | inherited, 17 | }) => { 18 | const entries = list(target, query, { 19 | childFirst: false, 20 | roots, 21 | leaves: false, 22 | sort, 23 | missing: false, 24 | entries: true, 25 | shallowArrays, 26 | classes, 27 | inherited, 28 | }) 29 | const entriesA = filterEntries({ entries, condition, target, entriesOpt }) 30 | return entriesA.reduce(setFunc, newTarget) 31 | } 32 | 33 | const filterEntries = ({ entries, condition, target, entriesOpt }) => 34 | condition === undefined 35 | ? entries 36 | : entries 37 | .filter((entry) => 38 | meetsCondition({ condition, entry, target, entriesOpt }), 39 | ) 40 | .filter(hasNoParentSet) 41 | 42 | const meetsCondition = ({ condition, entry, target, entriesOpt }) => { 43 | const entryA = entriesOpt ? entry : entry.value 44 | return condition(entryA, target) 45 | } 46 | 47 | // This is like the `roots` option. However, we cannot use that option since we 48 | // need to apply `condition()` first. 49 | const hasNoParentSet = ({ path: pathA }, indexA, entries) => 50 | entries.every( 51 | (entryB, indexB) => indexA <= indexB || !isParentPath(entryB.path, pathA), 52 | ) 53 | -------------------------------------------------------------------------------- /src/main.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/max-params */ 2 | import type { Entry, Options, Query, Target } from 'wild-wild-path' 3 | 4 | type Value = Entry['value'] 5 | 6 | type MapValue = (value: never) => Value 7 | 8 | type MapEntry = (entry: Entry) => Entry 9 | 10 | type TestValue = (value: never) => boolean 11 | 12 | type TestEntry = (entry: Entry) => boolean 13 | 14 | type OptionsWithEntries = Options & { entries: true } 15 | 16 | /** 17 | * Use a `mapFunction()` to modify any property matching the `query`. 18 | * 19 | * @example 20 | * ```js 21 | * const target = { user: { firstName: 'Alice', lastName: 'Smith' } } 22 | * map(target, 'user.*', (userProp) => userProp.toLowerCase()) 23 | * // { user: { firstName: 'alice', lastName: 'smith' } } 24 | * ``` 25 | */ 26 | export function map( 27 | target: Target, 28 | query: Query, 29 | mapFunction: T extends OptionsWithEntries ? MapEntry : MapValue, 30 | options?: T, 31 | ): Target 32 | 33 | /** 34 | * Deeply merge an object `value` with each object property matching the `query`. 35 | * 36 | * If one of these properties is not an object, it is overridden instead. 37 | * 38 | * [Any object in `value` can change](https://github.com/ehmicky/declarative-merge#nesting) 39 | * the merge mode using a `_merge` property with value 40 | * [`"deep"`](https://github.com/ehmicky/declarative-merge#deep-merge) (default), 41 | * [`"shallow"`](https://github.com/ehmicky/declarative-merge#shallow-merge), 42 | * [`"set"`](https://github.com/ehmicky/declarative-merge#no-merge) or 43 | * [`"delete"`](https://github.com/ehmicky/declarative-merge#delete). 44 | * 45 | * Arrays 46 | * [can be merged using objects in `value`](https://github.com/ehmicky/declarative-merge#arrays) 47 | * where the keys are the 48 | * [array indices](https://github.com/ehmicky/declarative-merge#update). Items can 49 | * be [updated](https://github.com/ehmicky/declarative-merge#update), 50 | * [merged](https://github.com/ehmicky/declarative-merge#merge), 51 | * [added](https://github.com/ehmicky/declarative-merge#add), 52 | * [inserted](https://github.com/ehmicky/declarative-merge#insert), 53 | * [appended](https://github.com/ehmicky/declarative-merge#append), 54 | * [prepended](https://github.com/ehmicky/declarative-merge#prepend) or 55 | * [deleted](https://github.com/ehmicky/declarative-merge#delete-1). 56 | * 57 | * @example 58 | * ```js 59 | * const target = { 60 | * userOne: { names: ['Alice', 'Smith'], settings: { deleted: true } }, 61 | * userTwo: { names: ['John', 'Doe'], settings: { deleted: false } }, 62 | * } 63 | * 64 | * merge(target, '*', { age: 72, settings: { admin: true } }) 65 | * // { 66 | * // userOne: { 67 | * // names: ['Alice', 'Smith'], 68 | * // settings: { deleted: true, admin: true }, 69 | * // age: 72, 70 | * // }, 71 | * // userTwo: { 72 | * // names: ['John', 'Doe'], 73 | * // settings: { deleted: false, admin: true }, 74 | * // age: 72, 75 | * // }, 76 | * // } 77 | * 78 | * merge(target, '*', { age: 72, settings: { admin: true }, _merge: 'shallow' }) 79 | * // { 80 | * // userOne: { 81 | * // names: [ 'Alice', 'Smith' ], 82 | * // settings: { admin: true }, 83 | * // age: 72, 84 | * // }, 85 | * // userTwo: { 86 | * // names: [ 'John', 'Doe' ], 87 | * // settings: { admin: true }, 88 | * // age: 72, 89 | * // }, 90 | * // } 91 | * 92 | * merge(target, '*', { names: { 1: 'Red' } }) 93 | * // { 94 | * // userOne: { 95 | * // names: ['Alice', 'Red'], 96 | * // settings: { deleted: true, admin: true }, 97 | * // age: 72, 98 | * // }, 99 | * // userTwo: { 100 | * // names: ['John', 'Red'], 101 | * // settings: { deleted: false, admin: true }, 102 | * // age: 72, 103 | * // }, 104 | * // } 105 | * ``` 106 | */ 107 | export function merge( 108 | target: Target, 109 | query: Query, 110 | value: unknown, 111 | options?: Options, 112 | ): Target 113 | 114 | /** 115 | * Concatenate an array of `values` with each array property matching the 116 | * `query`. 117 | * If one of these properties is not an array, it is overridden instead. 118 | * 119 | * @example 120 | * ```js 121 | * const target = { 122 | * userOne: { firstName: 'Alice', colors: ['red'] }, 123 | * userTwo: { firstName: 'John', colors: ['blue'] }, 124 | * } 125 | * push(target, '*.colors', ['yellow', 'silver']) 126 | * // { 127 | * // userOne: { firstName: 'Alice', colors: ['red', 'yellow', 'silver'] }, 128 | * // userTwo: { firstName: 'John', colors: ['blue', 'yellow', 'silver'] }, 129 | * // } 130 | * ``` 131 | */ 132 | export function push( 133 | target: Target, 134 | query: Query, 135 | values: readonly unknown[], 136 | options?: Options, 137 | ): Target 138 | 139 | /** 140 | * Like `push()` but concatenates at the beginning of each property instead of 141 | * at the end. 142 | * 143 | * @example 144 | * ```js 145 | * const target = { 146 | * userOne: { firstName: 'Alice', colors: ['red'] }, 147 | * userTwo: { firstName: 'John', colors: ['blue'] }, 148 | * } 149 | * unshift(target, '*.colors', ['yellow', 'silver']) 150 | * // { 151 | * // userOne: { firstName: 'Alice', colors: ['yellow', 'silver', 'red'] }, 152 | * // userTwo: { firstName: 'John', colors: ['yellow', 'silver', 'blue'] }, 153 | * // } 154 | * ``` 155 | */ 156 | export function unshift( 157 | target: Target, 158 | query: Query, 159 | values: readonly unknown[], 160 | options?: Options, 161 | ): Target 162 | 163 | /** 164 | * Return the first property that matches the `query` and that returns `true` 165 | * with the `testFunction()`. 166 | * 167 | * @example 168 | * ```js 169 | * const target = { 170 | * userOne: { firstName: 'Alice', colors: ['red'] }, 171 | * userTwo: { firstName: 'John', colors: ['blue'] }, 172 | * } 173 | * find(target, '*.firstName', (firstName) => firstName !== 'John') // 'Alice' 174 | * ``` 175 | */ 176 | export function find( 177 | target: Target, 178 | query: Query, 179 | testFunction: T extends OptionsWithEntries ? TestEntry : TestValue, 180 | options?: T, 181 | ): T extends OptionsWithEntries ? Entry : Value 182 | 183 | /** 184 | * Keep only the properties matching the `query`. 185 | * 186 | * @example 187 | * ```js 188 | * const target = { 189 | * userOne: { firstName: 'Alice', lastName: 'Smith', age: 72, admin: true }, 190 | * userTwo: { firstName: 'John', lastName: 'Doe', age: 72, admin: true }, 191 | * } 192 | * pick(target, '*./Name/') 193 | * // { 194 | * // userOne: { firstName: 'Alice', lastName: 'Smith' }, 195 | * // userTwo: { firstName: 'John', lastName: 'Doe' }, 196 | * // } 197 | * ``` 198 | */ 199 | export function pick(target: Target, query: Query, options?: Options): Target 200 | 201 | /** 202 | * Keep only the properties that match the `query` and that return `true` with 203 | * the `testFunction()`. 204 | * 205 | * @example 206 | * ```js 207 | * const target = { 208 | * userOne: { firstName: 'Alice', lastName: 'Smith', age: 72, admin: true }, 209 | * userTwo: { firstName: 'John', lastName: 'Doe', age: 72, admin: true }, 210 | * } 211 | * include(target, '**', (value) => typeof value === 'string') 212 | * // { 213 | * // userOne: { firstName: 'Alice', lastName: 'Smith' }, 214 | * // userTwo: { firstName: 'John', lastName: 'Doe' }, 215 | * // } 216 | * ``` 217 | */ 218 | export function include( 219 | target: Target, 220 | query: Query, 221 | testFunction: T extends OptionsWithEntries ? TestEntry : TestValue, 222 | options?: T, 223 | ): Target 224 | 225 | /** 226 | * Remove any property that matches the `query` and that returns `true` with the 227 | * `testFunction()`. 228 | * 229 | * @example 230 | * ```js 231 | * const target = { 232 | * userOne: { firstName: 'Alice', lastName: 'Smith', age: 72, admin: true }, 233 | * userTwo: { firstName: 'John', lastName: 'Doe', age: 72, admin: true }, 234 | * } 235 | * exclude(target, '**', (value) => typeof value === 'string') 236 | * // { 237 | * // userOne: { age: 72, admin: true }, 238 | * // userTwo: { age: 72, admin: true }, 239 | * // } 240 | * ``` 241 | */ 242 | export function exclude( 243 | target: Target, 244 | query: Query, 245 | testFunction: T extends OptionsWithEntries ? TestEntry : TestValue, 246 | options?: T, 247 | ): Target 248 | 249 | /** 250 | * Flatten deep properties to shallow properties with 251 | * [dot-delimited paths](https://github.com/ehmicky/wild-wild-path#paths). 252 | * 253 | * @example 254 | * ```js 255 | * const target = { user: { firstName: 'Bob', colors: ['red', 'blue'] } } 256 | * flatten(target) 257 | * // { 'user.firstName': 'Bob', 'user.colors.0': 'red', 'user.colors.1': 'blue' } 258 | * ``` 259 | */ 260 | export function flatten(target: Target, options?: Options): object 261 | /* eslint-enable @typescript-eslint/max-params */ 262 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | export { find } from './find.js' 2 | export { pick } from './include/pick.js' 3 | export { include } from './include/include.js' 4 | export { exclude } from './include/exclude.js' 5 | export { map } from './map.js' 6 | export { push, unshift } from './merge/array.js' 7 | export { merge } from './merge/object.js' 8 | export { flatten } from './flatten.js' 9 | -------------------------------------------------------------------------------- /src/main.test-d.ts: -------------------------------------------------------------------------------- 1 | import { expectNotType, expectType } from 'tsd' 2 | import type { Entry, Target } from 'wild-wild-path' 3 | 4 | import { 5 | exclude, 6 | find, 7 | flatten, 8 | include, 9 | map, 10 | merge, 11 | pick, 12 | push, 13 | unshift, 14 | } from 'wild-wild-utils' 15 | 16 | const mapValue = (value: unknown): unknown => value 17 | const mapEntry = (entry: Entry): Entry => entry 18 | const testValue = (value: unknown): boolean => true 19 | const testEntry = (entry: Entry): boolean => true 20 | 21 | expectType(map({}, 'prop', mapValue)) 22 | map({}, ['prop'], mapEntry) 23 | map({}, 'prop', mapEntry, { entries: true }) 24 | // @ts-expect-error 25 | map(true, 'prop', mapEntry) 26 | // @ts-expect-error 27 | map({}, true, mapEntry) 28 | // @ts-expect-error 29 | map({}, 'prop', true) 30 | // @ts-expect-error 31 | map({}, 'prop', mapEntry, true) 32 | 33 | expectType(find({}, 'prop', testValue)) 34 | expectType(find({}, 'prop', testEntry, { entries: true })) 35 | expectNotType(find({}, 'prop', testEntry, { entries: false })) 36 | find({}, ['prop'], testValue) 37 | // @ts-expect-error 38 | find(true, 'prop', testEntry) 39 | // @ts-expect-error 40 | find({}, true, testEntry) 41 | // @ts-expect-error 42 | find({}, 'prop', true) 43 | // @ts-expect-error 44 | find({}, 'prop', testEntry, true) 45 | 46 | expectType(pick({}, 'prop')) 47 | pick({}, ['prop']) 48 | pick({}, 'prop', { entries: true }) 49 | // @ts-expect-error 50 | pick(true, 'prop') 51 | // @ts-expect-error 52 | pick({}, true) 53 | // @ts-expect-error 54 | pick({}, 'prop', true) 55 | 56 | expectType(include({}, 'prop', testValue)) 57 | include({}, ['prop'], testValue) 58 | include({}, 'prop', testEntry, { entries: true }) 59 | // @ts-expect-error 60 | include(true, 'prop', testEntry) 61 | // @ts-expect-error 62 | include({}, true, testEntry) 63 | // @ts-expect-error 64 | include({}, 'prop', true) 65 | // @ts-expect-error 66 | include({}, 'prop', testEntry, true) 67 | 68 | expectType(exclude({}, 'prop', testValue)) 69 | exclude({}, ['prop'], testValue) 70 | exclude({}, 'prop', testEntry, { entries: true }) 71 | // @ts-expect-error 72 | exclude(true, 'prop', testEntry) 73 | // @ts-expect-error 74 | exclude({}, true, testEntry) 75 | // @ts-expect-error 76 | exclude({}, 'prop', true) 77 | // @ts-expect-error 78 | exclude({}, 'prop', testEntry, true) 79 | 80 | expectType(merge({}, 'prop', { one: 1 })) 81 | merge({}, ['prop'], { one: 1 }) 82 | merge({}, 'prop', true) 83 | // @ts-expect-error 84 | merge(true, 'prop', { one: 1 }) 85 | // @ts-expect-error 86 | merge({}, true, { one: 1 }) 87 | // @ts-expect-error 88 | merge({}, 'prop', { one: 1 }, true) 89 | 90 | expectType(push({}, 'prop', [1])) 91 | push({}, ['prop'], [1]) 92 | push({}, 'prop', [1], { sort: true }) 93 | // @ts-expect-error 94 | push(true, 'prop', [1]) 95 | // @ts-expect-error 96 | push({}, true, [1]) 97 | // @ts-expect-error 98 | push({}, 'prop', true) 99 | // @ts-expect-error 100 | push({}, 'prop', [1], true) 101 | 102 | expectType(unshift({}, 'prop', [1])) 103 | unshift({}, ['prop'], [1]) 104 | unshift({}, 'prop', [1], { sort: true }) 105 | // @ts-expect-error 106 | unshift(true, 'prop', [1]) 107 | // @ts-expect-error 108 | unshift({}, true, [1]) 109 | // @ts-expect-error 110 | unshift({}, 'prop', true) 111 | // @ts-expect-error 112 | unshift({}, 'prop', [1], true) 113 | 114 | expectType(flatten({})) 115 | expectType(flatten([])) 116 | flatten({}, { shallowArrays: true }) 117 | // @ts-expect-error 118 | flatten(true) 119 | // @ts-expect-error 120 | flatten({}, true) 121 | -------------------------------------------------------------------------------- /src/map.js: -------------------------------------------------------------------------------- 1 | // We split the core methods of `wild-wild-path` to keep it small, and provide 2 | // additional utilities built on top of it. 3 | import { get, list, set } from 'wild-wild-path' 4 | 5 | import { validateFunction } from './validate.js' 6 | 7 | // Map values matching a query. 8 | // Missing entries are mapped too 9 | // - This allows logic such as adding default values 10 | // - However, if the map function does not modify the value, we do not set it 11 | // We recurse from children to parents: 12 | // - This allows recursive logic such as cleaning up empty objects 13 | // - This also means newly set values are not recursed over: 14 | // - There are not many use cases for it 15 | // - When needed, this can also be done by the consumer logic 16 | // - This also avoids infinite recursion 17 | export const map = ( 18 | target, 19 | query, 20 | mapFunc, 21 | { 22 | mutate, 23 | roots, 24 | leaves, 25 | missing, 26 | entries: entriesOpt, 27 | shallowArrays, 28 | classes, 29 | inherited, 30 | } = {}, 31 | // eslint-disable-next-line max-params 32 | ) => { 33 | validateFunction(mapFunc) 34 | const entries = list(target, query, { 35 | childFirst: true, 36 | roots, 37 | leaves, 38 | sort: false, 39 | missing, 40 | entries: true, 41 | shallowArrays, 42 | classes, 43 | inherited, 44 | }) 45 | return entries.reduce( 46 | (targetA, entry) => 47 | mapEntry({ 48 | mapFunc, 49 | target: targetA, 50 | entry, 51 | mutate, 52 | missing, 53 | entriesOpt, 54 | shallowArrays, 55 | classes, 56 | inherited, 57 | }), 58 | target, 59 | ) 60 | } 61 | 62 | const mapEntry = ({ 63 | mapFunc, 64 | target, 65 | entry, 66 | entry: { path }, 67 | mutate, 68 | missing, 69 | entriesOpt, 70 | shallowArrays, 71 | classes, 72 | inherited, 73 | }) => { 74 | const value = get(target, path, { shallowArrays, classes, inherited }) 75 | const entryA = entriesOpt ? { ...entry, value } : value 76 | const mappedValue = mapFunc(entryA) 77 | return value === mappedValue 78 | ? target 79 | : set(target, path, mappedValue, { 80 | mutate, 81 | missing, 82 | shallowArrays, 83 | classes, 84 | inherited, 85 | }) 86 | } 87 | -------------------------------------------------------------------------------- /src/map.test.js: -------------------------------------------------------------------------------- 1 | import { identity } from './helpers/functions.test.js' 2 | import { getChild } from './helpers/inherited.test.js' 3 | import { testMutate } from './helpers/mutate.test.js' 4 | import { testValidation } from './helpers/validate.test.js' 5 | 6 | import { map } from 'wild-wild-utils' 7 | 8 | const addOne = (value) => value + 1 9 | 10 | const removeEmpty = (object) => 11 | Object.values(object).every(isEmptyObj) ? {} : object 12 | 13 | const isEmptyObj = (object) => Object.keys(object).length === 0 14 | 15 | const addOneProp = (object) => ({ ...object, one: 1 }) 16 | 17 | const addDefaultOne = (value = 1) => value 18 | 19 | testMutate('map', map, [ 20 | // Main usage 21 | { input: [{ one: 1, two: 2 }, '*', identity], output: { one: 1, two: 2 } }, 22 | { input: [{ one: 1, two: 2 }, '*', addOne], output: { one: 2, two: 3 } }, 23 | { input: [{}, 'one', addOne], output: {} }, 24 | 25 | // `leaves` and `roots` options 26 | { 27 | input: [{ one: { two: {} } }, '*.**', addOneProp], 28 | output: { one: { one: 1, two: { one: 1 } } }, 29 | }, 30 | { 31 | input: [{ one: { two: {} } }, '*.**', addOneProp], 32 | opts: { leaves: true }, 33 | output: { one: { two: { one: 1 } } }, 34 | }, 35 | { 36 | input: [{ one: { two: { three: {} } } }, '*.**', removeEmpty], 37 | output: { one: {} }, 38 | }, 39 | { 40 | input: [{ one: { two: { three: {} } } }, '*.**', removeEmpty], 41 | opts: { roots: true }, 42 | output: { one: { two: { three: {} } } }, 43 | }, 44 | 45 | // `entries` option 46 | { 47 | input: [{ one: 1 }, 'one', identity], 48 | opts: { entries: true }, 49 | output: { one: { value: 1, path: ['one'], missing: false } }, 50 | }, 51 | { 52 | input: [{}, 'one', identity], 53 | opts: { entries: true, missing: true }, 54 | output: { one: { value: undefined, path: ['one'], missing: true } }, 55 | }, 56 | 57 | // `missing` option 58 | { 59 | input: [{ one: 1 }, 'one two', addDefaultOne], 60 | opts: { missing: true }, 61 | output: { one: 1, two: 1 }, 62 | }, 63 | 64 | // `shallowArrays` option 65 | { input: [[1], '*', addOne], output: [2] }, 66 | { input: [[1], '*', addOne, { shallowArrays: true }], output: [1] }, 67 | 68 | // `classes` and `inherited` options 69 | { input: [getChild(), '/own/', addOne], output: getChild() }, 70 | { 71 | input: [getChild(), '/own/', addOne], 72 | opts: { classes: true, mutate: true }, 73 | output: getChild({ own: 'own1' }), 74 | }, 75 | { input: [getChild(), '/inherited/', addOne], output: getChild() }, 76 | { 77 | input: [getChild(), '/inherited/', addOne], 78 | opts: { classes: true, mutate: true }, 79 | output: getChild(), 80 | }, 81 | { 82 | input: [getChild(), '/inherited/', addOne], 83 | opts: { classes: true, inherited: true, mutate: true }, 84 | output: getChild({ inherited: 'inherited1' }), 85 | }, 86 | ]) 87 | 88 | testValidation('map', map, [ 89 | [{}, true, identity], 90 | [{}, '.', true], 91 | ]) 92 | -------------------------------------------------------------------------------- /src/merge/array.js: -------------------------------------------------------------------------------- 1 | import { validateArray } from '../validate.js' 2 | 3 | import { mergeValues } from './common.js' 4 | 5 | // Like `set()` but push|unshift an array of values to the target array instead 6 | // eslint-disable-next-line max-params 7 | const mergeArrayValues = (mergeFunc, target, query, newValueArray, opts) => { 8 | validateArray(newValueArray) 9 | return mergeValues(mergeFunc, target, query, newValueArray, opts) 10 | } 11 | 12 | const pushValue = (value, newValueArray, { mutate }) => { 13 | if (!Array.isArray(value)) { 14 | return newValueArray 15 | } 16 | 17 | return mutate 18 | ? pushValueMutate(value, newValueArray) 19 | : pushValueClone(value, newValueArray) 20 | } 21 | 22 | const pushValueMutate = (value, newValueArray) => { 23 | // eslint-disable-next-line fp/no-loops 24 | for (const newValue of newValueArray) { 25 | // eslint-disable-next-line fp/no-mutating-methods 26 | value.push(newValue) 27 | } 28 | 29 | return value 30 | } 31 | 32 | const pushValueClone = (value, newValueArray) => [...value, ...newValueArray] 33 | 34 | export const push = mergeArrayValues.bind(undefined, pushValue) 35 | 36 | const unshiftValue = (value, newValueArray, { mutate }) => { 37 | if (!Array.isArray(value)) { 38 | return newValueArray 39 | } 40 | 41 | return mutate 42 | ? unshiftValueMutate(value, newValueArray) 43 | : unshiftValueClone(value, newValueArray) 44 | } 45 | 46 | const unshiftValueMutate = (value, newValueArray) => { 47 | // eslint-disable-next-line fp/no-loops, fp/no-let, fp/no-mutation 48 | for (let index = newValueArray.length - 1; index >= 0; index -= 1) { 49 | // eslint-disable-next-line fp/no-mutating-methods 50 | value.unshift(newValueArray[index]) 51 | } 52 | 53 | return value 54 | } 55 | 56 | const unshiftValueClone = (value, newValueArray) => [...newValueArray, ...value] 57 | 58 | // Like `push()` but from the beginning 59 | export const unshift = mergeArrayValues.bind(undefined, unshiftValue) 60 | -------------------------------------------------------------------------------- /src/merge/array.test.js: -------------------------------------------------------------------------------- 1 | import { getChild } from '../helpers/inherited.test.js' 2 | import { testMutate } from '../helpers/mutate.test.js' 3 | import { testOutput } from '../helpers/output.test.js' 4 | import { testValidation } from '../helpers/validate.test.js' 5 | 6 | import { push, unshift } from 'wild-wild-utils' 7 | 8 | testMutate('unshift', unshift, [ 9 | { input: [{ one: [1] }, 'one', [2]], output: { one: [2, 1] } }, 10 | { input: [{ one: [1] }, 'one', [2, 3]], output: { one: [2, 3, 1] } }, 11 | { input: [{ one: 1 }, 'one', [2]], output: { one: [2] } }, 12 | ]) 13 | 14 | testMutate('push', push, [ 15 | // Main usage 16 | { input: [{ one: [1] }, 'one', [2]], output: { one: [1, 2] } }, 17 | { input: [{ one: [1] }, 'one', [2, 3]], output: { one: [1, 2, 3] } }, 18 | { input: [{ one: 1 }, 'one', [2]], output: { one: [2] } }, 19 | 20 | // `leaves` and `roots` options 21 | { input: [{ one: [[1]] }, 'one one.0', [2]], output: { one: [[1, 2], 2] } }, 22 | { 23 | input: [{ one: [[1]] }, 'one one.0', [2]], 24 | opts: { leaves: true }, 25 | output: { one: [[1, 2]] }, 26 | }, 27 | { 28 | input: [{ one: [[1]] }, 'one one.0', [2]], 29 | opts: { roots: true }, 30 | output: { one: [[1], 2] }, 31 | }, 32 | 33 | // `missing` option 34 | { input: [{ one: [1] }, 'two', [2]], output: { one: [1], two: [2] } }, 35 | { 36 | input: [{ one: [1] }, 'two', [2]], 37 | opts: { missing: false }, 38 | output: { one: [1] }, 39 | }, 40 | 41 | // `shallowArrays` option 42 | { input: [[[1]], '*', [2]], output: [[1, 2]] }, 43 | { input: [[[1]], '*', [2], { shallowArrays: true }], output: [[1]] }, 44 | ]) 45 | 46 | testOutput('push', push, [ 47 | // `classes` option 48 | { 49 | input: [getChild({ own: [1] }), '/own/', [2], { mutate: true }], 50 | output: getChild({ own: [1] }), 51 | }, 52 | { 53 | input: [ 54 | getChild({ own: [1] }), 55 | '/own/', 56 | [2], 57 | { classes: true, mutate: true }, 58 | ], 59 | output: getChild({ own: [1, 2] }), 60 | }, 61 | ]) 62 | 63 | const invalidArguments = [ 64 | [{}, true, [1]], 65 | [{}, '.', 1], 66 | ] 67 | 68 | testValidation('push', push, invalidArguments) 69 | testValidation('unshift', unshift, invalidArguments) 70 | -------------------------------------------------------------------------------- /src/merge/common.js: -------------------------------------------------------------------------------- 1 | import { map } from '../map.js' 2 | 3 | // Wrapper around map() 4 | export const mergeValues = ( 5 | mapFunc, 6 | target, 7 | query, 8 | newValue, 9 | { 10 | mutate, 11 | roots, 12 | leaves, 13 | missing = true, 14 | shallowArrays, 15 | classes, 16 | inherited, 17 | } = {}, 18 | // eslint-disable-next-line max-params 19 | ) => 20 | map(target, query, (value) => mapFunc(value, newValue, { mutate }), { 21 | mutate, 22 | roots, 23 | leaves, 24 | missing, 25 | entries: false, 26 | shallowArrays, 27 | classes, 28 | inherited, 29 | }) 30 | -------------------------------------------------------------------------------- /src/merge/object.js: -------------------------------------------------------------------------------- 1 | import declarativeMerge from 'declarative-merge' 2 | 3 | import { mergeValues } from './common.js' 4 | 5 | // The `inherited`, `classes` and `mutate` options: 6 | // - Impact which properties are selected and how they are set 7 | // - But do not impact the merging logic itself, where those options are always 8 | // considered `false`. 9 | // Non-enumerable properties are ignored. 10 | const mergeValue = (value, newValue) => declarativeMerge(value, newValue) 11 | 12 | // Merge object values 13 | export const merge = mergeValues.bind(undefined, mergeValue) 14 | -------------------------------------------------------------------------------- /src/merge/object.test.js: -------------------------------------------------------------------------------- 1 | import { getChild } from '../helpers/inherited.test.js' 2 | import { testMutate } from '../helpers/mutate.test.js' 3 | import { testOutput } from '../helpers/output.test.js' 4 | import { testValidation } from '../helpers/validate.test.js' 5 | 6 | import { merge } from 'wild-wild-utils' 7 | 8 | testMutate('merge', merge, [ 9 | // Setting values 10 | { input: [{ one: { two: 2 } }, 'one', 3], output: { one: 3 } }, 11 | { input: [{ one: 3 }, 'one', { two: 2 }], output: { one: { two: 2 } } }, 12 | 13 | // Merging values 14 | { 15 | input: [{ one: { two: 2 } }, 'one', { three: 3 }], 16 | output: { one: { two: 2, three: 3 } }, 17 | }, 18 | 19 | // Overriding values 20 | { 21 | input: [{ one: { two: 2 } }, 'one', { two: 3 }], 22 | output: { one: { two: 3 } }, 23 | }, 24 | { 25 | input: [{ one: 2 }, 'one', { two: 3 }], 26 | output: { one: { two: 3 } }, 27 | }, 28 | 29 | // Merge modes 30 | { 31 | input: [{ one: { two: { three: 3 } } }, 'one', { two: { four: 0 } }], 32 | output: { one: { two: { three: 3, four: 0 } } }, 33 | }, 34 | { 35 | input: [ 36 | { one: { two: { three: 3 } } }, 37 | 'one', 38 | { two: { four: 0, _merge: 'set' } }, 39 | ], 40 | output: { one: { two: { four: 0 } } }, 41 | }, 42 | { 43 | input: [ 44 | { one: { two: { three: 2 } } }, 45 | 'one', 46 | { two: { four: 1 }, _merge: 'shallow' }, 47 | ], 48 | output: { one: { two: { four: 1 } } }, 49 | }, 50 | { 51 | input: [ 52 | { one: { two: { three: 1 } } }, 53 | 'one', 54 | { two: { four: 0, _merge: 'delete' } }, 55 | ], 56 | output: { one: {} }, 57 | }, 58 | 59 | // Array merge 60 | { 61 | input: [{ one: { two: [{}] } }, 'one', { two: { 0: { three: 1 } } }], 62 | output: { one: { two: [{ three: 1 }] } }, 63 | }, 64 | 65 | // `missing` option 66 | { 67 | input: [{ one: { two: 2 } }, 'three', { two: 2 }], 68 | output: { one: { two: 2 }, three: { two: 2 } }, 69 | }, 70 | { 71 | input: [{ one: { two: 2 } }, 'three', { two: 2 }], 72 | opts: { missing: false }, 73 | output: { one: { two: 2 } }, 74 | }, 75 | 76 | // `leaves` and `roots` options 77 | { 78 | input: [{ one: { two: { three: 3 } } }, 'one one.two', { four: 0 }], 79 | output: { one: { two: { three: 3, four: 0 }, four: 0 } }, 80 | }, 81 | { 82 | output: { one: { two: { three: 3, four: 0 } } }, 83 | input: [{ one: { two: { three: 3 } } }, 'one one.two', { four: 0 }], 84 | opts: { leaves: true }, 85 | }, 86 | { 87 | input: [{ one: { two: { three: 3 } } }, 'one one.two', { four: 0 }], 88 | opts: { roots: true }, 89 | output: { one: { two: { three: 3 }, four: 0 } }, 90 | }, 91 | 92 | // `shallowArrays` option 93 | { input: [[{ one: 1 }], '*', { two: 2 }], output: [{ one: 1, two: 2 }] }, 94 | { 95 | input: [[{ one: 1 }], '*', { two: 2 }, { shallowArrays: true }], 96 | output: [{ one: 1 }], 97 | }, 98 | ]) 99 | 100 | testValidation('merge', merge, [ 101 | [{}, true, 1], 102 | [{}, '.', 1, { classes: true }], 103 | ]) 104 | 105 | testOutput('merge', merge, [ 106 | { 107 | input: [ 108 | getChild({ own: { one: 1 } }), 109 | '/own/', 110 | { two: 2 }, 111 | { mutate: true }, 112 | ], 113 | output: getChild({ own: { one: 1 } }), 114 | }, 115 | { 116 | input: [ 117 | getChild({ own: { one: 1 } }), 118 | '/own/', 119 | { two: 2 }, 120 | { classes: true, mutate: true }, 121 | ], 122 | output: getChild({ own: { one: 1, two: 2 } }), 123 | }, 124 | ...[false, true].map((classes) => ({ 125 | input: [ 126 | { one: { two: { own: { three: 3 } } } }, 127 | '/one/', 128 | { two: getChild({ own: { six: 0 } }) }, 129 | { classes, mutate: true }, 130 | ], 131 | output: { one: { two: getChild({ own: { six: 0 } }) } }, 132 | })), 133 | ]) 134 | -------------------------------------------------------------------------------- /src/validate.js: -------------------------------------------------------------------------------- 1 | export const validateFunction = (value) => { 2 | if (typeof value !== 'function') { 3 | throwInvalidArg(value, 'a function') 4 | } 5 | } 6 | 7 | export const validateArray = (value) => { 8 | if (!Array.isArray(value)) { 9 | throwInvalidArg(value, 'an array') 10 | } 11 | } 12 | 13 | const throwInvalidArg = (value, errorPrefix) => { 14 | throw new TypeError(`Argument must be ${errorPrefix}: ${value}`) 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@ehmicky/dev-tasks/tsconfig.json" 3 | } 4 | --------------------------------------------------------------------------------