14 |
Enmap')
117 | .replace(/\*\*Kind\*\*: global variable/g, '**Kind**: instance property of Enmap')
118 | .replace(/\n{3,}/g, '\n\n');
119 |
120 | const finalOutput = apiDocsHeader + processedOutput;
121 | await writeFile('./docs/api.md', finalOutput, 'utf8');
122 |
123 | console.log('✅ JSDoc-to-Markdown documentation saved to ./docs/api.md');
124 | return finalOutput;
125 | }
126 |
127 | async function generateTypeDoc() {
128 | console.log('🔷 Generating TypeDoc HTML documentation...');
129 |
130 | try {
131 | execSync('npx typedoc --out ./docs-typedoc --plugin default', { stdio: 'inherit' });
132 | console.log('✅ TypeDoc HTML documentation saved to ./docs-typedoc/');
133 | return true;
134 | } catch (error) {
135 | console.error('❌ TypeDoc HTML generation failed:', error.message);
136 | return false;
137 | }
138 | }
139 |
140 | async function generateTypeDocMarkdown() {
141 | console.log('📝 Generating TypeDoc Markdown for Retype...');
142 |
143 | try {
144 | execSync('npx typedoc', { stdio: 'inherit' });
145 |
146 | // Post-process the generated markdown files to fix angle bracket issues
147 | await fixMarkdownForRetype('./docs/typedoc');
148 |
149 | // Create the README.md file for the typedoc folder
150 | const retypeReadmeContent = `---
151 | icon: code
152 | expanded: true
153 | order: 90
154 | ---
155 |
156 | # API Reference
157 |
158 | Complete TypeScript API documentation for Enmap with full type information.
159 |
160 | :::hint{type="info"}
161 | This documentation is automatically generated from the TypeScript source code and includes complete type signatures, generics, and cross-references.
162 | :::
163 |
164 | ## Quick Navigation
165 |
166 | ### Core Classes
167 | - **[Enmap Class](classes/default.md)** - Main database class with all methods
168 |
169 | ### Interfaces
170 | - **[EnmapOptions](interfaces/EnmapOptions.md)** - Configuration options for Enmap
171 |
172 | ---
173 |
174 | ## Key Features
175 |
176 | ### TypeScript Support
177 | - **Full type safety** with generics \`Enmap\w+<\/code>/g) || []).length;
235 |
236 | console.log('📄 JSDoc-to-Markdown:');
237 | console.log(` • Output: ./docs/api.md`);
238 | console.log(` • Content: ${markdownOutput.length} characters`);
239 | console.log(` • Methods: ${methodCount}`);
240 | console.log(` • Properties: ${propertyCount}`);
241 | console.log(` • Use: npm run docs:markdown`);
242 | }
243 |
244 | if (typedocSuccess) {
245 | console.log('\n🔷 TypeDoc HTML:');
246 | console.log(` • Output: ./docs-typedoc/`);
247 | console.log(` • Features: Rich HTML interface with search`);
248 | console.log(` • Types: Full TypeScript type information`);
249 | console.log(` • Use: npm run docs:typedoc`);
250 | console.log(` • View: Open ./docs-typedoc/index.html in browser`);
251 | }
252 |
253 | if (retypeSuccess) {
254 | console.log('\n📖 Retype Integration:');
255 | console.log(` • Output: ./docs/typedoc/ (markdown)`);
256 | console.log(` • Features: TypeScript types + Retype styling`);
257 | console.log(` • Integration: ./docs/typedoc/README.md`);
258 | console.log(` • Use: npm run docs:retype`);
259 | console.log(` • View: Your existing Retype documentation site`);
260 | }
261 |
262 | console.log('\n💡 Recommendations:');
263 | console.log(' • Use Retype integration for your main docs (best of both worlds!)');
264 | console.log(' • Use TypeDoc HTML for development/API reference');
265 | console.log(' • JSDoc Markdown as fallback for existing workflows');
266 | }
267 |
268 | // Parse command line arguments
269 | const args = process.argv.slice(2);
270 | const format = args[0];
271 |
272 | async function main() {
273 | try {
274 | switch (format) {
275 | case 'markdown':
276 | case 'jsdoc':
277 | await generateJSDocMarkdown();
278 | break;
279 | case 'typedoc':
280 | case 'html':
281 | await generateTypeDoc();
282 | break;
283 | case 'retype':
284 | await generateTypeDocMarkdown();
285 | break;
286 | case 'all':
287 | case 'both':
288 | case undefined:
289 | await generateAllFormats();
290 | break;
291 | default:
292 | console.log('Usage: node generate-docs-enhanced.js [format]');
293 | console.log('Formats: markdown, typedoc, retype, all (default)');
294 | console.log('');
295 | console.log('Examples:');
296 | console.log(' node generate-docs-enhanced.js markdown # JSDoc markdown only');
297 | console.log(' node generate-docs-enhanced.js typedoc # TypeDoc HTML only');
298 | console.log(' node generate-docs-enhanced.js retype # TypeDoc markdown for Retype');
299 | console.log(' node generate-docs-enhanced.js all # All formats');
300 | process.exit(1);
301 | }
302 | } catch (error) {
303 | console.error('❌ Documentation generation failed:', error.message);
304 | process.exit(1);
305 | }
306 | }
307 |
308 | main();
309 |
--------------------------------------------------------------------------------
/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 | APPENDIX: Code from other projects
190 | This project contains partial code from Discord.js version 10.
191 | Project Link: https://github.com/discordjs/discord.js
192 | Author: Amish Shaw (hydrabolt)
193 | License: https://github.com/discordjs/discord.js/blob/master/LICENSE
194 |
195 |
196 | Copyright 2018 Évelyne Lachance
197 |
198 | Licensed under the Apache License, Version 2.0 (the "License");
199 | you may not use this file except in compliance with the License.
200 | You may obtain a copy of the License at
201 |
202 | http://www.apache.org/licenses/LICENSE-2.0
203 |
204 | Unless required by applicable law or agreed to in writing, software
205 | distributed under the License is distributed on an "AS IS" BASIS,
206 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
207 | See the License for the specific language governing permissions and
208 | limitations under the License.
209 |
--------------------------------------------------------------------------------
/test/index.spec.js:
--------------------------------------------------------------------------------
1 | import {
2 | describe,
3 | test,
4 | expect,
5 | vi,
6 | } from 'vitest';
7 | import { parse, stringify } from 'better-serialize';
8 | import Enmap from '../src/index.ts';
9 | import { mkdir, rm } from 'fs/promises';
10 | import CustomError from '../src/error.ts';
11 |
12 | describe('Enmap', () => {
13 | process.setMaxListeners(100);
14 |
15 | describe('can instantiate', () => {
16 | test('should create an Enmap', () => {
17 | const enmap = new Enmap({ inMemory: true });
18 |
19 | expect(enmap).toBeInstanceOf(Enmap);
20 | });
21 |
22 | test('should create an Enmap w/ warning', () => {
23 | const spy = vi.spyOn(console, 'warn');
24 |
25 | const enmap = new Enmap({ name: '::memory::' });
26 |
27 | expect(enmap).toBeInstanceOf(Enmap);
28 | expect(spy).toHaveBeenCalledTimes(1);
29 | });
30 |
31 | test('should create an Enmap w/ custom serializing', () => {
32 | const enmap = new Enmap({
33 | inMemory: true,
34 | serializer: JSON.stringify,
35 | deserializer: JSON.parse,
36 | });
37 |
38 | expect(enmap).toBeInstanceOf(Enmap);
39 | });
40 |
41 | test('should close database on exit', () => {
42 | let callback;
43 | process.on = (event, cb) => {
44 | if (event === 'exit') {
45 | callback = cb;
46 | }
47 | };
48 |
49 | const enmap = new Enmap({ inMemory: true });
50 |
51 | callback();
52 |
53 | expect(enmap.db.open).toBe(false);
54 | });
55 |
56 | test('should create a persistent Enmap w/ dir', async () => {
57 | await mkdir('./tmp').catch(() => {});
58 |
59 | const enmap = new Enmap({ name: 'test', dataDir: './tmp' });
60 |
61 | expect(enmap).toBeInstanceOf(Enmap);
62 | });
63 |
64 | test('should load a persistent Enmap w/ dir', () => {
65 | const enmap = new Enmap({ name: 'test', dataDir: './tmp' });
66 |
67 | expect(enmap).toBeInstanceOf(Enmap);
68 | });
69 |
70 | test('should fail to create a persistent Enmap w/o dir', async () => {
71 | expect(
72 | () => new Enmap({ name: 'test', dataDir: './data-not-found' }),
73 | ).toThrow(TypeError);
74 | });
75 |
76 | test('should create/use data dir', async () => {
77 | await rm('./data', { recursive: true }).catch(() => {});
78 |
79 | const enmap = new Enmap({ name: 'test' });
80 | const enmap2 = new Enmap({ name: 'test' });
81 |
82 | expect(enmap).toBeInstanceOf(Enmap);
83 | expect(enmap2).toBeInstanceOf(Enmap);
84 | });
85 | });
86 |
87 | describe('should manipulate data', () => {
88 | describe('set', () => {
89 | const enmap = new Enmap({ inMemory: true });
90 |
91 | test('should set a value w/ string', () => {
92 | enmap.set('setString', 'value');
93 |
94 | expect(enmap.get('setString')).toBe('value');
95 | });
96 |
97 | test('should set a value w/ object', () => {
98 | enmap.set('setObject', { value: 'value' });
99 |
100 | expect(enmap.get('setObject')).toEqual({ value: 'value' });
101 | });
102 |
103 | test('should set a value w/ array', () => {
104 | enmap.set('setArray', ['value']);
105 |
106 | expect(enmap.get('setArray')).toEqual(['value']);
107 | });
108 |
109 | test('should set a value w/ number', () => {
110 | enmap.set('setNumber', 1);
111 |
112 | expect(enmap.get('setNumber')).toBe(1);
113 | });
114 |
115 | test('should set a value w/ null', () => {
116 | enmap.set('setNull', null);
117 |
118 | expect(enmap.get('setNull')).toBe(null);
119 | });
120 |
121 | test('should set a value w/ boolean', () => {
122 | enmap.set('setBool', true);
123 |
124 | expect(enmap.get('setBool')).toBe(true);
125 | });
126 |
127 | test('should set a value w/ BigInt', () => {
128 | enmap.set('setBigInt', BigInt(1));
129 |
130 | expect(enmap.get('setBigInt')).toBe(BigInt(1));
131 | });
132 |
133 | test('should set a value w/ path', () => {
134 | enmap.set('setPath', 'value', 'sub');
135 |
136 | expect(enmap.get('setPath', 'sub')).toBe('value');
137 | });
138 |
139 | test('should fail to set a value w/ invalid key', () => {
140 | expect(() => enmap.set([], {}, () => {})).toThrow(
141 | `Invalid key for enmap - keys must be a string.`,
142 | );
143 | // I don't know what happened that made me think this wasn't valid...
144 | enmap.set('$', 'Dollar signs are accepted');
145 | expect(enmap.get('$')).toBe('Dollar signs are accepted');
146 | });
147 |
148 | test('should call callback after set', () => {
149 | const mock = vi.fn();
150 | enmap.changed(mock);
151 | enmap.set('setCallback', 'value', 'sub');
152 | expect(mock).toHaveBeenCalledTimes(1);
153 | expect(enmap.get('setCallback', 'sub')).toBe('value');
154 | });
155 | });
156 |
157 | describe('update', () => {
158 | const enmap = new Enmap({ inMemory: true });
159 | test('should update a value w/ object', () => {
160 | enmap.set('updateObj', { value: 'value' });
161 |
162 | enmap.update('updateObj', { value: 'new' });
163 |
164 | expect(enmap.get('updateObj')).toEqual({ value: 'new' });
165 | });
166 |
167 | test('should update a value w/ function', () => {
168 | enmap.set('updateFunc', { value: 1 });
169 |
170 | enmap.update('updateFunc', (val) => {
171 | return { value: val.value + 1 };
172 | });
173 |
174 | expect(enmap.get('updateFunc')).toEqual({ value: 2 });
175 | });
176 | });
177 |
178 | describe('get', () => {
179 | const enmap = new Enmap({ inMemory: true });
180 | const defaultEnmap = new Enmap({
181 | inMemory: true,
182 | autoEnsure: { hello: 'world' },
183 | });
184 |
185 | test('should get a value', () => {
186 | enmap.set('get', 'value');
187 |
188 | expect(enmap.get('get')).toBe('value');
189 | });
190 |
191 | test('should get a value w/ path', () => {
192 | enmap.set('getPath', 'value', 'sub');
193 |
194 | expect(enmap.get('getPath', 'sub')).toBe('value');
195 | });
196 |
197 | test('should get a value w/ default', () => {
198 | expect(defaultEnmap.get('unknown')).toEqual({ hello: 'world' });
199 | });
200 |
201 | test('should get a value w/ default', () => {
202 | expect(defaultEnmap.get('unknown', 'hello')).toBe('world');
203 | });
204 | });
205 |
206 | describe('observe', () => {
207 | const enmap = new Enmap({ inMemory: true });
208 | test('should observe a value', () => {
209 | enmap.set('observe', { value: 'value' });
210 | const observer = enmap.observe('observe');
211 |
212 | expect(observer).toEqual({ value: 'value' });
213 |
214 | observer.value = 'new';
215 |
216 | expect(enmap.get('observe')).toEqual({ value: 'new' });
217 | expect(observer).toEqual({ value: 'new' });
218 | });
219 | });
220 |
221 | describe('size', () => {
222 | const enmap = new Enmap({ inMemory: true });
223 | test('should get size', () => {
224 | enmap.set('size', 'value');
225 |
226 | expect(enmap.size).toBe(1);
227 | expect(enmap.count).toBe(1);
228 | expect(enmap.length).toBe(1);
229 | });
230 | });
231 |
232 | describe('keys', () => {
233 | const enmap = new Enmap({ inMemory: true });
234 |
235 | test('should get keys', () => {
236 | enmap.set('keys', 'value');
237 | expect(enmap.keys()).toEqual(['keys']);
238 | expect(enmap.indexes()).toEqual(['keys']);
239 | });
240 | });
241 |
242 | describe('values', () => {
243 | const enmap = new Enmap({ inMemory: true });
244 |
245 | test('should get values', () => {
246 | enmap.set('values', 'value');
247 | expect(enmap.values()).toEqual(['value']);
248 | });
249 | });
250 |
251 | describe('entries', () => {
252 | const enmap = new Enmap({ inMemory: true });
253 |
254 | test('should get entries', () => {
255 | enmap.set('entries', 'value');
256 | expect(enmap.entries()).toEqual([['entries', 'value']]);
257 | });
258 | });
259 |
260 | describe('autonum', () => {
261 | const enmap = new Enmap({ inMemory: true });
262 |
263 | test('should autonum', () => {
264 | expect(enmap.autonum).toBe('1');
265 | expect(enmap.autonum).toBe('2');
266 | });
267 | });
268 |
269 | describe('push', () => {
270 | const enmap = new Enmap({ inMemory: true });
271 |
272 | test('should push value', () => {
273 | enmap.set('push', []);
274 | enmap.push('push', 'value');
275 |
276 | expect(enmap.get('push')).toEqual(['value']);
277 | });
278 |
279 | test('should not push duplicate value', () => {
280 | enmap.set('pushDup', ['value']);
281 | enmap.push('pushDup', 'value');
282 |
283 | expect(enmap.get('pushDup')).toEqual(['value']);
284 | });
285 |
286 | test('should push duplicate value', () => {
287 | enmap.set('pushDup2', ['value']);
288 | enmap.push('pushDup2', 'value', null, true);
289 |
290 | expect(enmap.get('pushDup2')).toEqual(['value', 'value']);
291 | });
292 |
293 | test('should fail to push value w/ path to string', () => {
294 | enmap.set('pushObjStr', { sub: '' });
295 | expect(() => enmap.push('pushObjStr', 'value', 'sub')).toThrow(
296 | new CustomError('Key does not point to an array', 'EnmapPathError'),
297 | );
298 | });
299 |
300 | test('should push value w/ path', () => {
301 | enmap.set('pushObj', { sub: [] });
302 | enmap.push('pushObj', 'value', 'sub');
303 |
304 | expect(enmap.get('pushObj', 'sub')).toEqual(['value']);
305 | });
306 | });
307 |
308 | describe('math', () => {
309 | const enmap = new Enmap({ inMemory: true });
310 |
311 | test('should fail w/o base/op/opand', () => {
312 | enmap.set('math', 1);
313 |
314 | expect(() => enmap.math('math')).toThrow(
315 | new CustomError(
316 | 'Math Operation requires base and operation',
317 | 'EnmapTypeError',
318 | ),
319 | );
320 | });
321 |
322 | test('should add value', () => {
323 | enmap.set('simplevalue', 1);
324 | enmap.math('simplevalue', '+', 1);
325 | enmap.math('simplevalue', 'add', 1);
326 | enmap.math('simplevalue', 'addition', 1);
327 |
328 | expect(enmap.get('simplevalue')).toBe(4);
329 | });
330 |
331 | test('should subtract value', () => {
332 | enmap.set('simplevalue', 1);
333 | enmap.math('simplevalue', '-', 1);
334 | enmap.math('simplevalue', 'sub', 1);
335 | enmap.math('simplevalue', 'subtract', 1);
336 |
337 | expect(enmap.get('simplevalue')).toBe(-2);
338 | });
339 |
340 | test('should multiply value', () => {
341 | enmap.set('simplevalue', 2);
342 | enmap.math('simplevalue', '*', 2);
343 | enmap.math('simplevalue', 'mult', 2);
344 | enmap.math('simplevalue', 'multiply', 2);
345 |
346 | expect(enmap.get('simplevalue')).toBe(16);
347 | });
348 |
349 | test('should divide value', () => {
350 | enmap.set('simplevalue', 4);
351 | enmap.math('simplevalue', '/', 2);
352 | enmap.math('simplevalue', 'div', 2);
353 | enmap.math('simplevalue', 'divide', 2);
354 |
355 | expect(enmap.get('simplevalue')).toBe(0.5);
356 | });
357 |
358 | test('should exponent value', () => {
359 | enmap.set('simplevalue', 2);
360 | enmap.math('simplevalue', '^', 2);
361 | enmap.math('simplevalue', 'exp', 2);
362 | enmap.math('simplevalue', 'exponent', 2);
363 |
364 | expect(enmap.get('simplevalue')).toBe(256);
365 | });
366 |
367 | test('should modulo value', () => {
368 | enmap.set('simplevalue', 5);
369 | enmap.math('simplevalue', '%', 2);
370 | enmap.math('simplevalue', 'mod', 2);
371 | enmap.math('simplevalue', 'modulo', 2);
372 |
373 | expect(enmap.get('simplevalue')).toBe(1);
374 | });
375 |
376 | test('should random value', () => {
377 | enmap.set('rand', 1);
378 | enmap.math('rand', 'rand', 1);
379 |
380 | expect(enmap.get('rand')).toBeGreaterThanOrEqual(0);
381 | expect(enmap.get('rand')).toBeLessThanOrEqual(1);
382 | });
383 |
384 | test('should null value', () => {
385 | enmap.set('huh', 1);
386 | enmap.math('huh', 'huh', 1);
387 |
388 | expect(enmap.get('huh')).toBe(null);
389 | });
390 |
391 | test('should math value w/ path', () => {
392 | enmap.set('pathobj', { a: 1 });
393 | enmap.math('pathobj', 'sub', 1, 'a');
394 | expect(enmap.get('pathobj')).toEqual({ a: 0 });
395 | enmap.inc('pathobj', 'a');
396 | expect(enmap.get('pathobj')).toEqual({ a: 1 });
397 | enmap.dec('pathobj', 'a');
398 | expect(enmap.get('pathobj')).toEqual({ a: 0 });
399 | });
400 | });
401 |
402 | describe('inc', () => {
403 | const enmap = new Enmap({ inMemory: true });
404 |
405 | test('should increment value', () => {
406 | enmap.set('inc', 1);
407 | enmap.inc('inc');
408 |
409 | expect(enmap.get('inc')).toBe(2);
410 | });
411 | });
412 |
413 | describe('dec', () => {
414 | const enmap = new Enmap({ inMemory: true });
415 |
416 | test('should decrement value', () => {
417 | enmap.set('dec', 1);
418 | enmap.dec('dec');
419 |
420 | expect(enmap.get('dec')).toBe(0);
421 | });
422 | });
423 |
424 | describe('ensure', () => {
425 | const enmap = new Enmap({ inMemory: true });
426 | const defaultEnmap = new Enmap({
427 | inMemory: true,
428 | autoEnsure: { hello: 'world' },
429 | });
430 |
431 | test('should ensure value', () => {
432 | enmap.ensure('ensure', 'value');
433 |
434 | expect(enmap.get('ensure')).toBe('value');
435 | });
436 |
437 | test('should ensure value w/ existing value', () => {
438 | enmap.set('ensureExisting', 'value2');
439 | enmap.ensure('ensureExisting', 'value');
440 |
441 | expect(enmap.get('ensureExisting')).toBe('value2');
442 | });
443 |
444 | test('should ensure value w/ default', () => {
445 | expect(defaultEnmap.ensure('unknown')).toEqual({ hello: 'world' });
446 | });
447 |
448 | test('should ensure value w/ path', () => {
449 | enmap.ensure('ensurePath', 'value', 'sub');
450 |
451 | expect(enmap.get('ensurePath', 'sub')).toBe('value');
452 | });
453 |
454 | test('should ensure value w/ existing path', () => {
455 | enmap.set('ensurePathExisting', { sub: 'value2' });
456 | enmap.ensure('ensurePathExisting', 'value', 'sub');
457 |
458 | expect(enmap.get('ensurePathExisting', 'sub')).toBe('value2');
459 | });
460 |
461 | test('should fail to ensure string w/ object value', () => {
462 | enmap.set('ensureObj', { value: 'value' });
463 |
464 | expect(() => enmap.ensure('ensureObj', 'value')).toThrow(
465 | new CustomError(
466 | 'Default value for "ensureObj" in enmap "MemoryEnmap" must be an object when merging with an object value.',
467 | 'EnmapArgumentError',
468 | ),
469 | );
470 | });
471 |
472 | test('should ignore + warn ensure value w/ default', () => {
473 | const spy = vi.spyOn(process, 'emitWarning');
474 |
475 | expect(defaultEnmap.ensure('unknown', 'hello')).toEqual({
476 | hello: 'world',
477 | });
478 |
479 | expect(spy).toHaveBeenCalledTimes(1);
480 | });
481 | });
482 |
483 | describe('has', () => {
484 | const enmap = new Enmap({ inMemory: true });
485 |
486 | test('should return true if key exists', () => {
487 | enmap.set('has', 'value');
488 |
489 | expect(enmap.has('has')).toBe(true);
490 | });
491 |
492 | test("should return false if key doesn't exist", () => {
493 | expect(enmap.has('unknown')).toBe(false);
494 | });
495 | });
496 |
497 | describe('includes', () => {
498 | const enmap = new Enmap({ inMemory: true });
499 |
500 | test('should return true w/ value', () => {
501 | enmap.set('includes', ['value']);
502 |
503 | expect(enmap.includes('includes', 'value')).toBe(true);
504 | });
505 |
506 | test('should return false w/o value', () => {
507 | enmap.set('includes', ['value']);
508 |
509 | expect(enmap.includes('includes', 'value2')).toBe(false);
510 | });
511 | });
512 |
513 | describe('delete', () => {
514 | const enmap = new Enmap({ inMemory: true });
515 |
516 | test('should delete a key', () => {
517 | enmap.set('delete', 'value');
518 | enmap.delete('delete');
519 |
520 | expect(enmap.get('delete')).toBe(null);
521 | });
522 |
523 | test('should delete a path', () => {
524 | enmap.set('deletePath', 'value', 'sub');
525 | enmap.delete('deletePath', 'sub');
526 |
527 | expect(enmap.get('deletePath', 'sub')).toBe(undefined);
528 | });
529 | });
530 |
531 | describe('clear', () => {
532 | const enmap = new Enmap({ inMemory: true });
533 |
534 | test('should clear all keys', () => {
535 | enmap.set('clear', 'value');
536 | enmap.clear();
537 |
538 | expect(enmap.get('clear')).toBe(null);
539 | });
540 | });
541 |
542 | describe('remove', () => {
543 | const enmap = new Enmap({ inMemory: true });
544 |
545 | test('should remove a value', () => {
546 | enmap.set('remove', ['value']);
547 | enmap.remove('remove', 'value');
548 |
549 | expect(enmap.get('remove')).toEqual([]);
550 | });
551 |
552 | test('should remove a value w/ function', () => {
553 | enmap.set('remove', ['value', 'value2']);
554 | enmap.remove('remove', (val) => val === 'value');
555 |
556 | expect(enmap.get('remove')).toEqual(['value2']);
557 | });
558 |
559 | test('should remove a value w/ path', () => {
560 | enmap.set('removePath', { sub: ['value'] });
561 | enmap.remove('removePath', 'value', 'sub');
562 |
563 | expect(enmap.get('removePath', 'sub')).toEqual([]);
564 | });
565 | });
566 |
567 | describe('export', () => {
568 | const enmap = new Enmap({ inMemory: true });
569 |
570 | test('should export data', () => {
571 | enmap.set('export', 'value');
572 |
573 | const output = enmap.export();
574 |
575 | expect(parse(output)).toMatchObject({
576 | name: 'MemoryEnmap',
577 | exportDate: expect.any(Number),
578 | version: expect.any(String),
579 | keys: [{ key: 'export', value: stringify('value') }],
580 | });
581 | });
582 | });
583 |
584 | describe('import', () => {
585 | const enmap = new Enmap({ inMemory: true });
586 |
587 | test('should import data', () => {
588 | enmap.import(
589 | JSON.stringify({
590 | name: 'MemoryEnmap',
591 | exportDate: Date.now(),
592 | version: '1.0.0',
593 | keys: [{ key: 'import', value: stringify({ hello: 'world' }) }],
594 | }),
595 | );
596 |
597 | expect(enmap.get('import')).toEqual({ hello: 'world' });
598 | });
599 |
600 | test('should import data w/o overwrite', () => {
601 | enmap.set('import', 'value');
602 | enmap.import(
603 | JSON.stringify({
604 | name: 'MemoryEnmap',
605 | exportDate: Date.now(),
606 | version: '1.0.0',
607 | keys: [{ key: 'import', value: stringify({ hello: 'world' }) }],
608 | }),
609 | false,
610 | );
611 |
612 | expect(enmap.get('import')).toBe('value');
613 | });
614 |
615 | test('should import data w/ clear w/o overwrite', () => {
616 | enmap.set('import', 'value');
617 |
618 | enmap.import(
619 | JSON.stringify({
620 | name: 'MemoryEnmap',
621 | exportDate: Date.now(),
622 | version: '1.0.0',
623 | keys: [{ key: 'import', value: stringify({ hello: 'world' }) }],
624 | }),
625 | false,
626 | true,
627 | );
628 |
629 | expect(enmap.get('import')).toEqual({ hello: 'world' });
630 | });
631 |
632 | test('should fail to import invalid data', () => {
633 | expect(() => enmap.import('invalid')).toThrow(
634 | new CustomError('Data provided is not valid JSON', 'EnmapDataError'),
635 | );
636 | });
637 |
638 | test('should fail to import null data', () => {
639 | expect(() => enmap.import('null')).toThrow(
640 | new CustomError(
641 | 'No data provided for import() in "MemoryEnmap"',
642 | 'EnmapImportError',
643 | ),
644 | );
645 | });
646 | });
647 |
648 | describe('multi', () => {
649 | test('should create multiple Enmaps', () => {
650 | const enmaps = Enmap.multi(['multi1', 'multi2'], { inMemory: true });
651 |
652 | expect(enmaps).toEqual({
653 | multi1: expect.any(Enmap),
654 | multi2: expect.any(Enmap),
655 | });
656 | });
657 |
658 | test('should fail to create empty', () => {
659 | expect(() => Enmap.multi([])).toThrow(
660 | new CustomError(
661 | '"names" argument must be an array of string names.',
662 | 'EnmapTypeError',
663 | ),
664 | );
665 | });
666 | });
667 |
668 | describe('random', () => {
669 | const enmap = new Enmap({ inMemory: true });
670 |
671 | test('should get random value', () => {
672 | enmap.set('random', 'value');
673 |
674 | expect(enmap.random()).toEqual([['random', 'value']]);
675 | });
676 |
677 | test('should get random value w/ count', () => {
678 | enmap.set('random', 'value');
679 |
680 | expect(enmap.random(2).length).toBe(1);
681 |
682 | enmap.set('random2', 'value');
683 |
684 | expect(enmap.random(2).length).toBe(2);
685 | });
686 | });
687 |
688 | describe('randomKey', () => {
689 | const enmap = new Enmap({ inMemory: true });
690 |
691 | test('should get random key', () => {
692 | enmap.set('random', 'value');
693 |
694 | expect(enmap.randomKey()).toEqual(['random']);
695 | });
696 |
697 | test('should get random key w/ count', () => {
698 | enmap.set('random', 'value');
699 |
700 | expect(enmap.randomKey(2).length).toBe(1);
701 |
702 | enmap.set('random2', 'value');
703 |
704 | expect(enmap.randomKey(2).length).toBe(2);
705 | });
706 | });
707 |
708 | describe('every', () => {
709 | const enmap = new Enmap({ inMemory: true });
710 |
711 | test('should return true for all values w/ value', () => {
712 | enmap.set('every', 'value');
713 | enmap.set('every2', 'value');
714 |
715 | expect(enmap.every('value')).toBe(true);
716 | });
717 |
718 | test('should return true for all value w/ function', () => {
719 | enmap.set('every', 'value');
720 | enmap.set('every2', 'value');
721 |
722 | expect(enmap.every((val) => val === 'value')).toBe(true);
723 | });
724 |
725 | test('should return false for all values w/o value', () => {
726 | enmap.set('every', 'value');
727 | enmap.set('every2', 'value2');
728 |
729 | expect(enmap.every('value')).toBe(false);
730 | });
731 |
732 | test('should return false for all value w/ function', () => {
733 | enmap.set('every', 'value');
734 | enmap.set('every2', 'value2');
735 |
736 | expect(enmap.every((val) => val === 'value')).toBe(false);
737 | });
738 |
739 | test('should return false for all values w/ path', () => {
740 | enmap.set('every', { sub: 'value' });
741 | enmap.set('every2', { sub: 'value2' });
742 |
743 | expect(enmap.every('value', 'sub')).toBe(false);
744 | });
745 |
746 | test('should return true for all values w/ path', () => {
747 | enmap.set('every', { sub: 'value' });
748 | enmap.set('every2', { sub: 'value' });
749 |
750 | expect(enmap.every('value', 'sub')).toBe(true);
751 | });
752 | });
753 |
754 | describe('some', () => {
755 | const enmap = new Enmap({ inMemory: true });
756 |
757 | test('should return true for some values w/ value', () => {
758 | enmap.set('some', 'value');
759 | enmap.set('some2', 'value2');
760 |
761 | expect(enmap.some('value')).toBe(true);
762 | });
763 |
764 | test('should return true for some value w/ function', () => {
765 | enmap.set('some', 'value');
766 | enmap.set('some2', 'value2');
767 |
768 | expect(enmap.some((val) => val === 'value')).toBe(true);
769 | });
770 |
771 | test('should return false for some values w/o value', () => {
772 | enmap.set('some', 'value');
773 | enmap.set('some2', 'value2');
774 |
775 | expect(enmap.some('value3')).toBe(false);
776 | });
777 |
778 | test('should return false for some value w/ function', () => {
779 | enmap.set('some', 'value');
780 | enmap.set('some2', 'value2');
781 |
782 | expect(enmap.some((val) => val === 'value3')).toBe(false);
783 | });
784 |
785 | test('should return false for some values w/ path', () => {
786 | enmap.set('some', { sub: 'value' });
787 | enmap.set('some2', { sub: 'value2' });
788 |
789 | expect(enmap.some('value', 'sub')).toBe(true);
790 | });
791 |
792 | test('should return true for some values w/ path', () => {
793 | enmap.set('some', { sub: 'value' });
794 | enmap.set('some2', { sub: 'value' });
795 |
796 | expect(enmap.some('value', 'sub')).toBe(true);
797 | });
798 | });
799 |
800 | describe('map', () => {
801 | const enmap = new Enmap({ inMemory: true });
802 |
803 | test('should map values', () => {
804 | enmap.set('map', 'value');
805 | enmap.set('map2', 'value2');
806 |
807 | expect(enmap.map((val) => val)).toEqual(['value', 'value2']);
808 | });
809 |
810 | test('should map values w/ path', () => {
811 | enmap.set('map', { sub: 'value' });
812 | enmap.set('map2', { sub: 'value2' });
813 |
814 | expect(enmap.map('sub')).toEqual(['value', 'value2']);
815 | });
816 | });
817 |
818 | describe('find', () => {
819 | const enmap = new Enmap({ inMemory: true });
820 |
821 | test('should find value', () => {
822 | enmap.set('find', 'value');
823 | enmap.set('find2', 'value2');
824 |
825 | expect(enmap.find((val) => val === 'value')).toBe('value');
826 | });
827 |
828 | test('should find value w/ path', () => {
829 | enmap.set('find', { sub: 'value' });
830 | enmap.set('find2', { sub: 'value2' });
831 |
832 | expect(enmap.find('sub', 'value')).toEqual({ sub: 'value' });
833 | });
834 |
835 | test('should return null if not found', () => {
836 | enmap.set('find', 'value');
837 | enmap.set('find2', 'value2');
838 |
839 | expect(enmap.find((val) => val === 'value3')).toBe(null);
840 | });
841 | });
842 |
843 | describe('findIndex', () => {
844 | const enmap = new Enmap({ inMemory: true });
845 |
846 | test('should find index', () => {
847 | enmap.set('find', 'value');
848 | enmap.set('find2', 'value2');
849 |
850 | expect(enmap.findIndex((val) => val === 'value')).toBe('find');
851 | });
852 |
853 | test('should find index w/ path', () => {
854 | enmap.set('find', { sub: 'value' });
855 | enmap.set('find2', { sub: 'value2' });
856 |
857 | expect(enmap.findIndex('sub', 'value')).toBe('find');
858 | });
859 |
860 | test('should return null if not found', () => {
861 | enmap.set('find', 'value');
862 | enmap.set('find2', 'value2');
863 |
864 | expect(enmap.findIndex((val) => val === 'value3')).toBe(null);
865 | });
866 | });
867 |
868 | describe('reduce', () => {
869 | const enmap = new Enmap({ inMemory: true });
870 |
871 | test('should reduce values', () => {
872 | enmap.set('reduce', 1);
873 | enmap.set('reduce2', 2);
874 |
875 | expect(enmap.reduce((acc, val) => acc + val, 0)).toBe(3);
876 | });
877 |
878 | test('should reduce values w/ path', () => {
879 | enmap.set('reduce', { sub: 1 });
880 | enmap.set('reduce2', { sub: 2 });
881 |
882 | expect(enmap.reduce((acc, val) => acc + val.sub, 0)).toBe(3);
883 | });
884 | });
885 |
886 | describe('filter', () => {
887 | const enmap = new Enmap({ inMemory: true });
888 |
889 | test('should filter values', () => {
890 | enmap.set('filter', 'value');
891 | enmap.set('filter2', 'value2');
892 |
893 | expect(enmap.filter((val) => val === 'value')).toEqual(['value']);
894 | });
895 |
896 | test('should filter values w/ path', () => {
897 | enmap.set('filter', { sub: 'value' });
898 | enmap.set('filter2', { sub: 'value2' });
899 |
900 | expect(enmap.filter('sub', 'value')).toEqual([{ sub: 'value' }]);
901 | });
902 |
903 | test('should fail to filter w/o value', () => {
904 | enmap.set('filter', 'value');
905 | enmap.set('filter2', 'value2');
906 |
907 | expect(() => enmap.filter('value')).toThrow(
908 | new CustomError(
909 | 'Value is required for non-function predicate',
910 | 'EnmapValueError',
911 | ),
912 | );
913 | });
914 | });
915 |
916 | describe('sweep', () => {
917 | const enmap = new Enmap({ inMemory: true });
918 |
919 | test('should sweep values', () => {
920 | enmap.set('sweep', 'value');
921 | enmap.set('sweep2', 'value2');
922 |
923 | expect(enmap.sweep((val) => val === 'value')).toEqual(1);
924 | });
925 |
926 | test('should sweep values w/ path', () => {
927 | enmap.set('sweep', { sub: 'value' });
928 | enmap.set('sweep2', { sub: 'value2' });
929 |
930 | expect(enmap.sweep('sub', 'value')).toEqual(1);
931 | });
932 |
933 | test('should sweep values w/ function', () => {
934 | enmap.set('sweep', 'value');
935 | enmap.set('sweep2', 'value2');
936 |
937 | expect(enmap.sweep((val) => val === 'value')).toEqual(1);
938 | });
939 | });
940 |
941 | describe('partition', () => {
942 | const enmap = new Enmap({ inMemory: true });
943 |
944 | test('should partition values', () => {
945 | enmap.set('partition', 'value');
946 | enmap.set('partition2', 'value2');
947 |
948 | expect(enmap.partition((val) => val === 'value')).toEqual([
949 | ['value'],
950 | ['value2'],
951 | ]);
952 | });
953 |
954 | test('should partition values w/ path', () => {
955 | enmap.set('partition', { sub: 'value' });
956 | enmap.set('partition2', { sub: 'value2' });
957 |
958 | expect(enmap.partition('sub', 'value')).toEqual([
959 | [{ sub: 'value' }],
960 | [{ sub: 'value2' }],
961 | ]);
962 | });
963 | });
964 | });
965 | });
966 |
--------------------------------------------------------------------------------
/docs/typedoc/classes/default.md:
--------------------------------------------------------------------------------
1 | [**Enmap API Reference v6.1.3**](../README.md)
2 |
3 | ***
4 |
5 | [Enmap API Reference](../README.md) / default
6 |
7 | # default (V, SV)
8 |
9 | Defined in: [index.ts:77](https://github.com/eslachance/enmap/blob/main/src/index.ts#L77)
10 |
11 | A simple, synchronous, fast key/value storage build around better-sqlite3.
12 | Contains extra utility methods for managing arrays and objects.
13 |
14 | ## Type Parameters
15 |
16 | | Type Parameter | Default type |
17 | | ------ | ------ |
18 | | `V` | `any` |
19 | | `SV` | `unknown` |
20 |
21 | ## Constructors
22 |
23 | ### Constructor
24 |
25 | ```ts
26 | new default(options): Enmap;
27 | ```
28 |
29 | Defined in: [index.ts:109](https://github.com/eslachance/enmap/blob/main/src/index.ts#L109)
30 |
31 | Initializes a new Enmap, with options.
32 |
33 | #### Parameters
34 |
35 | | Parameter | Type | Description |
36 | | ------ | ------ | ------ |
37 | | `options` | [`EnmapOptions`](../interfaces/EnmapOptions.md)<`V`, `SV`> | Options for the enmap. See https://enmap.alterion.dev/usage#enmap-options for details. |
38 |
39 | #### Returns
40 |
41 | `Enmap`<`V`, `SV`>
42 |
43 | #### Example
44 |
45 | ```ts
46 | import Enmap from 'enmap';
47 | // Named, Persistent enmap
48 | const myEnmap = new Enmap({ name: "testing" });
49 |
50 | // Memory-only enmap
51 | const memoryEnmap = new Enmap({ inMemory: true });
52 |
53 | // Enmap that automatically assigns a default object when getting or setting anything.
54 | const autoEnmap = new Enmap({name: "settings", autoEnsure: { setting1: false, message: "default message"}})
55 | ```
56 |
57 | ## Accessors
58 |
59 | ### size
60 |
61 | #### Get Signature
62 |
63 | ```ts
64 | get size(): number;
65 | ```
66 |
67 | Defined in: [index.ts:292](https://github.com/eslachance/enmap/blob/main/src/index.ts#L292)
68 |
69 | Get the number of key/value pairs saved in the enmap.
70 |
71 | ##### Returns
72 |
73 | `number`
74 |
75 | The number of elements in the enmap.
76 |
77 | ***
78 |
79 | ### count
80 |
81 | #### Get Signature
82 |
83 | ```ts
84 | get count(): number;
85 | ```
86 |
87 | Defined in: [index.ts:300](https://github.com/eslachance/enmap/blob/main/src/index.ts#L300)
88 |
89 | ##### Returns
90 |
91 | `number`
92 |
93 | ***
94 |
95 | ### length
96 |
97 | #### Get Signature
98 |
99 | ```ts
100 | get length(): number;
101 | ```
102 |
103 | Defined in: [index.ts:304](https://github.com/eslachance/enmap/blob/main/src/index.ts#L304)
104 |
105 | ##### Returns
106 |
107 | `number`
108 |
109 | ***
110 |
111 | ### db
112 |
113 | #### Get Signature
114 |
115 | ```ts
116 | get db(): Database;
117 | ```
118 |
119 | Defined in: [index.ts:313](https://github.com/eslachance/enmap/blob/main/src/index.ts#L313)
120 |
121 | Get the better-sqlite3 database object. Useful if you want to directly query or interact with the
122 | underlying SQLite database. Use at your own risk, as errors here might cause loss of data or corruption!
123 |
124 | ##### Returns
125 |
126 | `Database`
127 |
128 | ***
129 |
130 | ### autonum
131 |
132 | #### Get Signature
133 |
134 | ```ts
135 | get autonum(): string;
136 | ```
137 |
138 | Defined in: [index.ts:327](https://github.com/eslachance/enmap/blob/main/src/index.ts#L327)
139 |
140 | Generates an automatic numerical key for inserting a new value.
141 | This is a "weak" method, it ensures the value isn't duplicated, but does not
142 | guarantee it's sequential (if a value is deleted, another can take its place).
143 | Useful for logging, actions, items, etc - anything that doesn't already have a unique ID.
144 |
145 | ##### Example
146 |
147 | ```ts
148 | enmap.set(enmap.autonum, "This is a new value");
149 | ```
150 |
151 | ##### Returns
152 |
153 | `string`
154 |
155 | The generated key number.
156 |
157 | ## Methods
158 |
159 | ### set()
160 |
161 | ```ts
162 | set(
163 | key,
164 | value,
165 | path?): this;
166 | ```
167 |
168 | Defined in: [index.ts:195](https://github.com/eslachance/enmap/blob/main/src/index.ts#L195)
169 |
170 | Sets a value in Enmap. If the key already has a value, overwrites the data (or the value in a path, if provided).
171 |
172 | #### Parameters
173 |
174 | | Parameter | Type | Description |
175 | | ------ | ------ | ------ |
176 | | `key` | `string` | Required. The location in which the data should be saved. |
177 | | `value` | `any` | Required. The value to write. Values must be serializable, which is done through (better-serialize)[https://github.com/RealShadowNova/better-serialize] If the value is not directly serializable, please use a custom serializer/deserializer. |
178 | | `path?` | `Path`<`V`, keyof `V`> | Optional. The path to the property to modify inside the value object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
179 |
180 | #### Returns
181 |
182 | `this`
183 |
184 | #### Example
185 |
186 | ```ts
187 | // Direct Value Examples
188 | enmap.set('simplevalue', 'this is a string');
189 | enmap.set('isEnmapGreat', true);
190 | enmap.set('TheAnswer', 42);
191 | enmap.set('IhazObjects', { color: 'black', action: 'paint', desire: true });
192 | enmap.set('ArraysToo', [1, "two", "tree", "foor"])
193 |
194 | // Settings Properties
195 | enmap.set('IhazObjects', 'blue', 'color'); //modified previous object
196 | enmap.set('ArraysToo', 'three', 2); // changes "tree" to "three" in array.
197 | ```
198 |
199 | ***
200 |
201 | ### get()
202 |
203 | ```ts
204 | get(key, path?): any;
205 | ```
206 |
207 | Defined in: [index.ts:221](https://github.com/eslachance/enmap/blob/main/src/index.ts#L221)
208 |
209 | Retrieves a value from the enmap, using its key.
210 |
211 | #### Parameters
212 |
213 | | Parameter | Type | Description |
214 | | ------ | ------ | ------ |
215 | | `key` | `string` | The key to retrieve from the enmap. |
216 | | `path?` | `Path`<`V`, keyof `V`> | Optional. The property to retrieve from the object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
217 |
218 | #### Returns
219 |
220 | `any`
221 |
222 | The parsed value for this key.
223 |
224 | #### Example
225 |
226 | ```ts
227 | const myKeyValue = enmap.get("myKey");
228 | console.log(myKeyValue);
229 |
230 | const someSubValue = enmap.get("anObjectKey", "someprop.someOtherSubProp");
231 | ```
232 |
233 | ***
234 |
235 | ### has()
236 |
237 | ```ts
238 | has(key): boolean;
239 | ```
240 |
241 | Defined in: [index.ts:250](https://github.com/eslachance/enmap/blob/main/src/index.ts#L250)
242 |
243 | Returns whether or not the key exists in the Enmap.
244 |
245 | #### Parameters
246 |
247 | | Parameter | Type | Description |
248 | | ------ | ------ | ------ |
249 | | `key` | `string` | Required. The key of the element to add to The Enmap or array. |
250 |
251 | #### Returns
252 |
253 | `boolean`
254 |
255 | #### Example
256 |
257 | ```ts
258 | if(enmap.has("myKey")) {
259 | // key is there
260 | }
261 | ```
262 |
263 | ***
264 |
265 | ### delete()
266 |
267 | ```ts
268 | delete(key, path?): this;
269 | ```
270 |
271 | Defined in: [index.ts:263](https://github.com/eslachance/enmap/blob/main/src/index.ts#L263)
272 |
273 | Deletes a key in the Enmap.
274 |
275 | #### Parameters
276 |
277 | | Parameter | Type | Description |
278 | | ------ | ------ | ------ |
279 | | `key` | `string` | Required. The key of the element to delete from The Enmap. |
280 | | `path?` | `Path`<`V`, keyof `V`> | Optional. The name of the property to remove from the object. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
281 |
282 | #### Returns
283 |
284 | `this`
285 |
286 | ***
287 |
288 | ### clear()
289 |
290 | ```ts
291 | clear(): void;
292 | ```
293 |
294 | Defined in: [index.ts:282](https://github.com/eslachance/enmap/blob/main/src/index.ts#L282)
295 |
296 | Deletes everything from the enmap.
297 |
298 | #### Returns
299 |
300 | `void`
301 |
302 | ***
303 |
304 | ### keys()
305 |
306 | ```ts
307 | keys(): string[];
308 | ```
309 |
310 | Defined in: [index.ts:348](https://github.com/eslachance/enmap/blob/main/src/index.ts#L348)
311 |
312 | Get all the keys of the enmap as an array.
313 |
314 | #### Returns
315 |
316 | `string`[]
317 |
318 | An array of all the keys in the enmap.
319 |
320 | ***
321 |
322 | ### indexes()
323 |
324 | ```ts
325 | indexes(): string[];
326 | ```
327 |
328 | Defined in: [index.ts:357](https://github.com/eslachance/enmap/blob/main/src/index.ts#L357)
329 |
330 | #### Returns
331 |
332 | `string`[]
333 |
334 | ***
335 |
336 | ### values()
337 |
338 | ```ts
339 | values(): V[];
340 | ```
341 |
342 | Defined in: [index.ts:365](https://github.com/eslachance/enmap/blob/main/src/index.ts#L365)
343 |
344 | Get all the values of the enmap as an array.
345 |
346 | #### Returns
347 |
348 | `V`[]
349 |
350 | An array of all the values in the enmap.
351 |
352 | ***
353 |
354 | ### entries()
355 |
356 | ```ts
357 | entries(): [string, V][];
358 | ```
359 |
360 | Defined in: [index.ts:378](https://github.com/eslachance/enmap/blob/main/src/index.ts#L378)
361 |
362 | Get all entries of the enmap as an array, with each item containing the key and value.
363 |
364 | #### Returns
365 |
366 | \[`string`, `V`\][]
367 |
368 | An array of arrays, with each sub-array containing two items, the key and the value.
369 |
370 | ***
371 |
372 | ### update()
373 |
374 | ```ts
375 | update(key, valueOrFunction): V;
376 | ```
377 |
378 | Defined in: [index.ts:413](https://github.com/eslachance/enmap/blob/main/src/index.ts#L413)
379 |
380 | Update an existing object value in Enmap by merging new keys. **This only works on objects**, any other value will throw an error.
381 | Heavily inspired by setState from React's class components.
382 | This is very useful if you have many different values to update and don't want to have more than one .set(key, value, prop) lines.
383 |
384 | #### Parameters
385 |
386 | | Parameter | Type | Description |
387 | | ------ | ------ | ------ |
388 | | `key` | `string` | The key of the object to update. |
389 | | `valueOrFunction` | `Partial`<`V`> \| (`data`) => `V` | Either an object to merge with the existing value, or a function that provides the existing object and expects a new object as a return value. In the case of a straight value, the merge is recursive and will add any missing level. If using a function, it is your responsibility to merge the objects together correctly. |
390 |
391 | #### Returns
392 |
393 | `V`
394 |
395 | The modified (merged) value.
396 |
397 | #### Example
398 |
399 | ```ts
400 | // Define an object we're going to update
401 | enmap.set("obj", { a: 1, b: 2, c: 3 });
402 |
403 | // Direct merge
404 | enmap.update("obj", { d: 4, e: 5 });
405 | // obj is now { a: 1, b: 2, c: 3, d: 4, e: 5 }
406 |
407 | // Functional update
408 | enmap.update("obj", (previous) => ({
409 | ...obj,
410 | f: 6,
411 | g: 7
412 | }));
413 | // this example takes heavy advantage of the spread operators.
414 | // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
415 | ```
416 |
417 | ***
418 |
419 | ### observe()
420 |
421 | ```ts
422 | observe(key, path?): any;
423 | ```
424 |
425 | Defined in: [index.ts:433](https://github.com/eslachance/enmap/blob/main/src/index.ts#L433)
426 |
427 | Returns an observable object. Modifying this object or any of its properties/indexes/children
428 | will automatically save those changes into enmap. This only works on
429 | objects and arrays, not "basic" values like strings or integers.
430 |
431 | #### Parameters
432 |
433 | | Parameter | Type | Description |
434 | | ------ | ------ | ------ |
435 | | `key` | `string` | The key to retrieve from the enmap. |
436 | | `path?` | `Path`<`V`, keyof `V`> | Optional. The property to retrieve from the object or array. |
437 |
438 | #### Returns
439 |
440 | `any`
441 |
442 | The value for this key.
443 |
444 | ***
445 |
446 | ### push()
447 |
448 | ```ts
449 | push(
450 | key,
451 | value,
452 | path?,
453 | allowDupes?): this;
454 | ```
455 |
456 | Defined in: [index.ts:457](https://github.com/eslachance/enmap/blob/main/src/index.ts#L457)
457 |
458 | Push to an array value in Enmap.
459 |
460 | #### Parameters
461 |
462 | | Parameter | Type | Default value | Description |
463 | | ------ | ------ | ------ | ------ |
464 | | `key` | `string` | `undefined` | Required. The key of the array element to push to in Enmap. |
465 | | `value` | `V` | `undefined` | Required. The value to push to the array. |
466 | | `path?` | `Path`<`V`, keyof `V`> | `undefined` | Optional. The path to the property to modify inside the value object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
467 | | `allowDupes?` | `boolean` | `false` | Optional. Allow duplicate values in the array (default: false). |
468 |
469 | #### Returns
470 |
471 | `this`
472 |
473 | #### Example
474 |
475 | ```ts
476 | // Assuming
477 | enmap.set("simpleArray", [1, 2, 3, 4]);
478 | enmap.set("arrayInObject", {sub: [1, 2, 3, 4]});
479 |
480 | enmap.push("simpleArray", 5); // adds 5 at the end of the array
481 | enmap.push("arrayInObject", "five", "sub"); // adds "five" at the end of the sub array
482 | ```
483 |
484 | ***
485 |
486 | ### math()
487 |
488 | ```ts
489 | math(
490 | key,
491 | operation,
492 | operand,
493 | path?): null | number;
494 | ```
495 |
496 | Defined in: [index.ts:487](https://github.com/eslachance/enmap/blob/main/src/index.ts#L487)
497 |
498 | Executes a mathematical operation on a value and saves it in the enmap.
499 |
500 | #### Parameters
501 |
502 | | Parameter | Type | Description |
503 | | ------ | ------ | ------ |
504 | | `key` | `string` | The enmap key on which to execute the math operation. |
505 | | `operation` | `MathOps` | Which mathematical operation to execute. Supports most math ops: =, -, *, /, %, ^, and english spelling of those operations. |
506 | | `operand` | `number` | The right operand of the operation. |
507 | | `path?` | `Path`<`V`, keyof `V`> | Optional. The property path to execute the operation on, if the value is an object or array. |
508 |
509 | #### Returns
510 |
511 | `null` \| `number`
512 |
513 | The updated value after the operation
514 |
515 | #### Example
516 |
517 | ```ts
518 | // Assuming
519 | points.set("number", 42);
520 | points.set("numberInObject", {sub: { anInt: 5 }});
521 |
522 | points.math("number", "/", 2); // 21
523 | points.math("number", "add", 5); // 26
524 | points.math("number", "modulo", 3); // 2
525 | points.math("numberInObject", "+", 10, "sub.anInt");
526 | ```
527 |
528 | ***
529 |
530 | ### inc()
531 |
532 | ```ts
533 | inc(key, path?): this;
534 | ```
535 |
536 | Defined in: [index.ts:512](https://github.com/eslachance/enmap/blob/main/src/index.ts#L512)
537 |
538 | Increments a key's value or property by 1. Value must be a number, or a path to a number.
539 |
540 | #### Parameters
541 |
542 | | Parameter | Type | Description |
543 | | ------ | ------ | ------ |
544 | | `key` | `string` | The enmap key where the value to increment is stored. |
545 | | `path?` | `Path`<`V`, keyof `V`> | Optional. The property path to increment, if the value is an object or array. |
546 |
547 | #### Returns
548 |
549 | `this`
550 |
551 | The udpated value after incrementing.
552 |
553 | #### Example
554 |
555 | ```ts
556 | // Assuming
557 | points.set("number", 42);
558 | points.set("numberInObject", {sub: { anInt: 5 }});
559 |
560 | points.inc("number"); // 43
561 | points.inc("numberInObject", "sub.anInt"); // {sub: { anInt: 6 }}
562 | ```
563 |
564 | ***
565 |
566 | ### dec()
567 |
568 | ```ts
569 | dec(key, path?): this;
570 | ```
571 |
572 | Defined in: [index.ts:533](https://github.com/eslachance/enmap/blob/main/src/index.ts#L533)
573 |
574 | Decrements a key's value or property by 1. Value must be a number, or a path to a number.
575 |
576 | #### Parameters
577 |
578 | | Parameter | Type | Description |
579 | | ------ | ------ | ------ |
580 | | `key` | `string` | The enmap key where the value to decrement is stored. |
581 | | `path?` | `Path`<`V`, keyof `V`> | Optional. The property path to decrement, if the value is an object or array. |
582 |
583 | #### Returns
584 |
585 | `this`
586 |
587 | The enmap.
588 |
589 | #### Example
590 |
591 | ```ts
592 | // Assuming
593 | points.set("number", 42);
594 | points.set("numberInObject", {sub: { anInt: 5 }});
595 |
596 | points.dec("number"); // 41
597 | points.dec("numberInObject", "sub.anInt"); // {sub: { anInt: 4 }}
598 | ```
599 |
600 | ***
601 |
602 | ### ensure()
603 |
604 | ```ts
605 | ensure(
606 | key,
607 | defaultValue,
608 | path?): any;
609 | ```
610 |
611 | Defined in: [index.ts:559](https://github.com/eslachance/enmap/blob/main/src/index.ts#L559)
612 |
613 | Returns the key's value, or the default given, ensuring that the data is there.
614 | This is a shortcut to "if enmap doesn't have key, set it, then get it" which is a very common pattern.
615 |
616 | #### Parameters
617 |
618 | | Parameter | Type | Description |
619 | | ------ | ------ | ------ |
620 | | `key` | `string` | Required. The key you want to make sure exists. |
621 | | `defaultValue` | `any` | Required. The value you want to save in the database and return as default. |
622 | | `path?` | `Path`<`V`, keyof `V`> | Optional. If presents, ensures both the key exists as an object, and the full path exists. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
623 |
624 | #### Returns
625 |
626 | `any`
627 |
628 | The value from the database for the key, or the default value provided for a new key.
629 |
630 | #### Example
631 |
632 | ```ts
633 | // Simply ensure the data exists (for using property methods):
634 | enmap.ensure("mykey", {some: "value", here: "as an example"});
635 | enmap.has("mykey"); // always returns true
636 | enmap.get("mykey", "here") // returns "as an example";
637 |
638 | // Get the default value back in a variable:
639 | const settings = mySettings.ensure("1234567890", defaultSettings);
640 | console.log(settings) // enmap's value for "1234567890" if it exists, otherwise the defaultSettings value.
641 | ```
642 |
643 | ***
644 |
645 | ### includes()
646 |
647 | ```ts
648 | includes(
649 | key,
650 | value,
651 | path?): boolean;
652 | ```
653 |
654 | Defined in: [index.ts:607](https://github.com/eslachance/enmap/blob/main/src/index.ts#L607)
655 |
656 | Performs Array.includes() on a certain enmap value. Works similar to
657 | [Array.includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes).
658 |
659 | #### Parameters
660 |
661 | | Parameter | Type | Description |
662 | | ------ | ------ | ------ |
663 | | `key` | `string` | Required. The key of the array to check the value of. |
664 | | `value` | `V` | Required. The value to check whether it's in the array. |
665 | | `path?` | `Path`<`V`, keyof `V`> | Optional. The property to access the array inside the value object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
666 |
667 | #### Returns
668 |
669 | `boolean`
670 |
671 | Whether the array contains the value.
672 |
673 | ***
674 |
675 | ### remove()
676 |
677 | ```ts
678 | remove(
679 | key,
680 | val,
681 | path?): this;
682 | ```
683 |
684 | Defined in: [index.ts:632](https://github.com/eslachance/enmap/blob/main/src/index.ts#L632)
685 |
686 | Remove a value in an Array or Object element in Enmap. Note that this only works for
687 | values, not keys. Note that only one value is removed, no more. Arrays of objects must use a function to remove,
688 | as full object matching is not supported.
689 |
690 | #### Parameters
691 |
692 | | Parameter | Type | Description |
693 | | ------ | ------ | ------ |
694 | | `key` | `string` | Required. The key of the element to remove from in Enmap. |
695 | | `val` | `V` \| (`value`) => `boolean` | Required. The value to remove from the array or object. OR a function to match an object. If using a function, the function provides the object value and must return a boolean that's true for the object you want to remove. |
696 | | `path?` | `Path`<`V`, keyof `V`> | Optional. The name of the array property to remove from. Should be a path with dot notation, such as "prop1.subprop2.subprop3". If not presents, removes directly from the value. |
697 |
698 | #### Returns
699 |
700 | `this`
701 |
702 | #### Example
703 |
704 | ```ts
705 | // Assuming
706 | enmap.set('array', [1, 2, 3])
707 | enmap.set('objectarray', [{ a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 }])
708 |
709 | enmap.remove('array', 1); // value is now [2, 3]
710 | enmap.remove('objectarray', (value) => value.e === 5); // value is now [{ a: 1, b: 2, c: 3 }]
711 | ```
712 |
713 | ***
714 |
715 | ### export()
716 |
717 | ```ts
718 | export(): string;
719 | ```
720 |
721 | Defined in: [index.ts:650](https://github.com/eslachance/enmap/blob/main/src/index.ts#L650)
722 |
723 | Exports the enmap data to stringified JSON format.
724 | **__WARNING__**: Does not work on memory enmaps containing complex data!
725 |
726 | #### Returns
727 |
728 | `string`
729 |
730 | The enmap data in a stringified JSON format.
731 |
732 | ***
733 |
734 | ### import()
735 |
736 | ```ts
737 | import(
738 | data,
739 | overwrite,
740 | clear): this;
741 | ```
742 |
743 | Defined in: [index.ts:673](https://github.com/eslachance/enmap/blob/main/src/index.ts#L673)
744 |
745 | Import an existing json export from enmap. This data must have been exported from enmap,
746 | and must be from a version that's equivalent or lower than where you're importing it.
747 | (This means Enmap 5 data is compatible in Enmap 6).
748 |
749 | #### Parameters
750 |
751 | | Parameter | Type | Default value | Description |
752 | | ------ | ------ | ------ | ------ |
753 | | `data` | `string` | `undefined` | The data to import to Enmap. Must contain all the required fields provided by an enmap export(). |
754 | | `overwrite` | `boolean` | `true` | Defaults to `true`. Whether to overwrite existing key/value data with incoming imported data |
755 | | `clear` | `boolean` | `false` | Defaults to `false`. Whether to clear the enmap of all data before importing (**__WARNING__**: Any existing data will be lost! This cannot be undone.) |
756 |
757 | #### Returns
758 |
759 | `this`
760 |
761 | ***
762 |
763 | ### multi()
764 |
765 | ```ts
766 | static multi(names, options?): Record>;
767 | ```
768 |
769 | Defined in: [index.ts:715](https://github.com/eslachance/enmap/blob/main/src/index.ts#L715)
770 |
771 | Initialize multiple Enmaps easily.
772 |
773 | #### Type Parameters
774 |
775 | | Type Parameter | Default type |
776 | | ------ | ------ |
777 | | `V` | `unknown` |
778 | | `SV` | `unknown` |
779 |
780 | #### Parameters
781 |
782 | | Parameter | Type | Description |
783 | | ------ | ------ | ------ |
784 | | `names` | `string`[] | Array of strings. Each array entry will create a separate enmap with that name. |
785 | | `options?` | `Omit`<[`EnmapOptions`](../interfaces/EnmapOptions.md)\<`V`, `SV`>, `"name"`\> | Options object to pass to each enmap, excluding the name.. |
786 |
787 | #### Returns
788 |
789 | `Record`<`string`, `Enmap`\<`V`, `SV`>\>
790 |
791 | An array of initialized Enmaps.
792 |
793 | #### Example
794 |
795 | ```ts
796 | // Using local variables.
797 | const Enmap = require('enmap');
798 | const { settings, tags, blacklist } = Enmap.multi(['settings', 'tags', 'blacklist']);
799 |
800 | // Attaching to an existing object (for instance some API's client)
801 | import Enmap from 'enmap';
802 | Object.assign(client, Enmap.multi(["settings", "tags", "blacklist"]));
803 | ```
804 |
805 | ***
806 |
807 | ### random()
808 |
809 | ```ts
810 | random(count?): [string, V][];
811 | ```
812 |
813 | Defined in: [index.ts:738](https://github.com/eslachance/enmap/blob/main/src/index.ts#L738)
814 |
815 | Obtains random value(s) from this Enmap. This relies on Enmap#array.
816 |
817 | #### Parameters
818 |
819 | | Parameter | Type | Default value | Description |
820 | | ------ | ------ | ------ | ------ |
821 | | `count?` | `number` | `1` | Number of values to obtain randomly |
822 |
823 | #### Returns
824 |
825 | \[`string`, `V`\][]
826 |
827 | The single value if `count` is undefined,
828 | or an array of values of `count` length
829 |
830 | ***
831 |
832 | ### randomKey()
833 |
834 | ```ts
835 | randomKey(count?): string[];
836 | ```
837 |
838 | Defined in: [index.ts:755](https://github.com/eslachance/enmap/blob/main/src/index.ts#L755)
839 |
840 | Obtains random key(s) from this Enmap. This relies on Enmap#keyArray
841 |
842 | #### Parameters
843 |
844 | | Parameter | Type | Default value | Description |
845 | | ------ | ------ | ------ | ------ |
846 | | `count?` | `number` | `1` | Number of keys to obtain randomly |
847 |
848 | #### Returns
849 |
850 | `string`[]
851 |
852 | The single key if `count` is undefined,
853 | or an array of keys of `count` length
854 |
855 | ***
856 |
857 | ### every()
858 |
859 | ```ts
860 | every(valueOrFunction, path?): boolean;
861 | ```
862 |
863 | Defined in: [index.ts:775](https://github.com/eslachance/enmap/blob/main/src/index.ts#L775)
864 |
865 | Similar to
866 | [Array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every).
867 | Supports either a predicate function or a value to compare.
868 | Returns true only if the predicate function returns true for all elements in the array (or the value is strictly equal in all elements).
869 |
870 | #### Parameters
871 |
872 | | Parameter | Type | Description |
873 | | ------ | ------ | ------ |
874 | | `valueOrFunction` | `any` | Function used to test (should return a boolean), or a value to compare. |
875 | | `path?` | `Path`<`V`, keyof `V`> | Required if the value is an object. The path to the property to compare with. |
876 |
877 | #### Returns
878 |
879 | `boolean`
880 |
881 | ***
882 |
883 | ### some()
884 |
885 | ```ts
886 | some(valueOrFunction, path?): boolean;
887 | ```
888 |
889 | Defined in: [index.ts:802](https://github.com/eslachance/enmap/blob/main/src/index.ts#L802)
890 |
891 | Similar to
892 | [Array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some).
893 | Supports either a predicate function or a value to compare.
894 | Returns true if the predicate function returns true for at least one element in the array (or the value is equal in at least one element).
895 |
896 | #### Parameters
897 |
898 | | Parameter | Type | Description |
899 | | ------ | ------ | ------ |
900 | | `valueOrFunction` | `any` | Function used to test (should return a boolean), or a value to compare. |
901 | | `path?` | `Path`<`V`, keyof `V`> | Required if the value is an object. The path to the property to compare with. |
902 |
903 | #### Returns
904 |
905 | `boolean`
906 |
907 | ***
908 |
909 | ### map()
910 |
911 | ```ts
912 | map(pathOrFn): R[];
913 | ```
914 |
915 | Defined in: [index.ts:827](https://github.com/eslachance/enmap/blob/main/src/index.ts#L827)
916 |
917 | Similar to
918 | [Array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).
919 | Returns an array of the results of applying the callback to all elements.
920 |
921 | #### Type Parameters
922 |
923 | | Type Parameter |
924 | | ------ |
925 | | `R` |
926 |
927 | #### Parameters
928 |
929 | | Parameter | Type | Description |
930 | | ------ | ------ | ------ |
931 | | `pathOrFn` | `string` \| (`val`, `key`) => `R` | A function that produces an element of the new Array, or a path to the property to map. |
932 |
933 | #### Returns
934 |
935 | `R`[]
936 |
937 | ***
938 |
939 | ### find()
940 |
941 | ```ts
942 | find(pathOrFn, value?): null | V;
943 | ```
944 |
945 | Defined in: [index.ts:853](https://github.com/eslachance/enmap/blob/main/src/index.ts#L853)
946 |
947 | Searches for a single item where its specified property's value is identical to the given value
948 | (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is similar to
949 | [Array.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
950 |
951 | #### Parameters
952 |
953 | | Parameter | Type | Description |
954 | | ------ | ------ | ------ |
955 | | `pathOrFn` | `string` \| (`val`, `key`) => `boolean` | The path to the value to test against, or the function to test with |
956 | | `value?` | `any` | The expected value - only applicable and required if using a property for the first argument |
957 |
958 | #### Returns
959 |
960 | `null` \| `V`
961 |
962 | #### Examples
963 |
964 | ```ts
965 | enmap.find('username', 'Bob');
966 | ```
967 |
968 | ```ts
969 | enmap.find(val => val.username === 'Bob');
970 | ```
971 |
972 | ***
973 |
974 | ### findIndex()
975 |
976 | ```ts
977 | findIndex(pathOrFn, value?): null | string;
978 | ```
979 |
980 | Defined in: [index.ts:879](https://github.com/eslachance/enmap/blob/main/src/index.ts#L879)
981 |
982 | Searches for the key of a single item where its specified property's value is identical to the given value
983 | (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is similar to
984 | [Array.findIndex()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex).
985 |
986 | #### Parameters
987 |
988 | | Parameter | Type | Description |
989 | | ------ | ------ | ------ |
990 | | `pathOrFn` | `string` \| (`val`, `key`) => `boolean` | The path to the value to test against, or the function to test with |
991 | | `value?` | `any` | The expected value - only applicable and required if using a property for the first argument |
992 |
993 | #### Returns
994 |
995 | `null` \| `string`
996 |
997 | #### Examples
998 |
999 | ```ts
1000 | enmap.findIndex('username', 'Bob');
1001 | ```
1002 |
1003 | ```ts
1004 | enmap.findIndex(val => val.username === 'Bob');
1005 | ```
1006 |
1007 | ***
1008 |
1009 | ### reduce()
1010 |
1011 | ```ts
1012 | reduce(predicate, initialValue?): R;
1013 | ```
1014 |
1015 | Defined in: [index.ts:900](https://github.com/eslachance/enmap/blob/main/src/index.ts#L900)
1016 |
1017 | Similar to
1018 | [Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).
1019 |
1020 | #### Type Parameters
1021 |
1022 | | Type Parameter |
1023 | | ------ |
1024 | | `R` |
1025 |
1026 | #### Parameters
1027 |
1028 | | Parameter | Type | Description |
1029 | | ------ | ------ | ------ |
1030 | | `predicate` | (`accumulator`, `val`, `key`) => `R` | Function used to reduce, taking three arguments; `accumulator`, `currentValue`, `currentKey`. |
1031 | | `initialValue?` | `R` | Starting value for the accumulator |
1032 |
1033 | #### Returns
1034 |
1035 | `R`
1036 |
1037 | ***
1038 |
1039 | ### filter()
1040 |
1041 | ```ts
1042 | filter(pathOrFn, value?): V[];
1043 | ```
1044 |
1045 | Defined in: [index.ts:920](https://github.com/eslachance/enmap/blob/main/src/index.ts#L920)
1046 |
1047 | Similar to
1048 | [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).
1049 | Returns an array of values where the given function returns true for that value.
1050 | Alternatively you can provide a value and path to filter by using exact value matching.
1051 |
1052 | #### Parameters
1053 |
1054 | | Parameter | Type | Description |
1055 | | ------ | ------ | ------ |
1056 | | `pathOrFn` | `string` \| (`val`, `key`) => `boolean` | The path to the value to test against, or the function to test with. If using a function, this function should return a boolean. |
1057 | | `value?` | `any` | Value to use as `this` when executing function |
1058 |
1059 | #### Returns
1060 |
1061 | `V`[]
1062 |
1063 | ***
1064 |
1065 | ### sweep()
1066 |
1067 | ```ts
1068 | sweep(pathOrFn, value?): number;
1069 | ```
1070 |
1071 | Defined in: [index.ts:950](https://github.com/eslachance/enmap/blob/main/src/index.ts#L950)
1072 |
1073 | Deletes entries that satisfy the provided filter function or value matching.
1074 |
1075 | #### Parameters
1076 |
1077 | | Parameter | Type | Description |
1078 | | ------ | ------ | ------ |
1079 | | `pathOrFn` | `string` \| (`val`, `key`) => `boolean` | The path to the value to test against, or the function to test with. |
1080 | | `value?` | `any` | The expected value - only applicable and required if using a property for the first argument. |
1081 |
1082 | #### Returns
1083 |
1084 | `number`
1085 |
1086 | The number of removed entries.
1087 |
1088 | ***
1089 |
1090 | ### changed()
1091 |
1092 | ```ts
1093 | changed(cb): void;
1094 | ```
1095 |
1096 | Defined in: [index.ts:988](https://github.com/eslachance/enmap/blob/main/src/index.ts#L988)
1097 |
1098 | Function called whenever data changes within Enmap after the initial load.
1099 | Can be used to detect if another part of your code changed a value in enmap and react on it.
1100 |
1101 | #### Parameters
1102 |
1103 | | Parameter | Type | Description |
1104 | | ------ | ------ | ------ |
1105 | | `cb` | (`key`, `oldValue`, `newValue`) => `void` | A callback function that will be called whenever data changes in the enmap. |
1106 |
1107 | #### Returns
1108 |
1109 | `void`
1110 |
1111 | #### Example
1112 |
1113 | ```ts
1114 | enmap.changed((keyName, oldValue, newValue) => {
1115 | console.log(`Value of ${keyName} has changed from: \n${oldValue}\nto\n${newValue}`);
1116 | });
1117 | ```
1118 |
1119 | ***
1120 |
1121 | ### partition()
1122 |
1123 | ```ts
1124 | partition(pathOrFn, value?): [V[], V[]];
1125 | ```
1126 |
1127 | Defined in: [index.ts:998](https://github.com/eslachance/enmap/blob/main/src/index.ts#L998)
1128 |
1129 | Separates the Enmap into multiple arrays given a function that separates them.
1130 |
1131 | #### Parameters
1132 |
1133 | | Parameter | Type | Description |
1134 | | ------ | ------ | ------ |
1135 | | `pathOrFn` | `string` \| (`val`, `key`) => `boolean` | the path to the value to test against, or the function to test with. |
1136 | | `value?` | `any` | the value to use as a condition for partitioning. |
1137 |
1138 | #### Returns
1139 |
1140 | \[`V`[], `V`[]\]
1141 |
1142 | An array of arrays with the partitioned data.
1143 |
--------------------------------------------------------------------------------
/docs/api.md:
--------------------------------------------------------------------------------
1 | ---
2 | description: >-
3 | The complete and unadultered API documentation for every single method and
4 | property accessible in Enmap.
5 | ---
6 |
7 | # Full Documentation
8 |
9 | The following is the complete list of methods available in Enmap. As it is auto-generated from the source code and its comments, it's a little more "raw" than the Usage docs. However, it has the benefit of being more complete and usually more up to date than the manually written docs.
10 |
11 | {% hint style="warning" %}
12 | If you're doing a PR on the docs github, please do not manually edit the below contents, as it will be overwritten. Check the src/index.ts source code and change the comments there instead!
13 | {% endhint %}
14 |
15 |
16 |
17 | ## Enmap Class
18 |
19 | The Enmap class provides a simple, synchronous, fast key/value storage built around better-sqlite3.
20 | Contains extra utility methods for managing arrays and objects.
21 |
22 | ## Properties
23 |
24 |
25 | - size ⇒
number
26 | Get the number of key/value pairs saved in the enmap.
27 |
28 | - db ⇒
Database
29 | Get the better-sqlite3 database object. Useful if you want to directly query or interact with the
30 | underlying SQLite database. Use at your own risk, as errors here might cause loss of data or corruption!
31 |
32 | - autonum ⇒
string
33 | Generates an automatic numerical key for inserting a new value.
34 | This is a "weak" method, it ensures the value isn't duplicated, but does not
35 | guarantee it's sequential (if a value is deleted, another can take its place).
36 | Useful for logging, actions, items, etc - anything that doesn't already have a unique ID.
37 |
38 |
39 |
40 | ## Methods
41 |
42 |
43 | - set(key, value, path)
44 | Sets a value in Enmap. If the key already has a value, overwrites the data (or the value in a path, if provided).
45 |
46 | - get(key, path) ⇒
47 | Retrieves a value from the enmap, using its key.
48 |
49 | - has(key) ⇒
boolean
50 | Returns whether or not the key exists in the Enmap.
51 |
52 | - delete(key, path)
53 | Deletes a key in the Enmap.
54 |
55 | - clear() ⇒
void
56 | Deletes everything from the enmap.
57 |
58 | - keys() ⇒
Array.<string>
59 | Get all the keys of the enmap as an array.
60 |
61 | - values() ⇒
Array.<*>
62 | Get all the values of the enmap as an array.
63 |
64 | - entries() ⇒
Array.<Array.<*, *>>
65 | Get all entries of the enmap as an array, with each item containing the key and value.
66 |
67 | - update(key, valueOrFunction) ⇒
*
68 | Update an existing object value in Enmap by merging new keys. This only works on objects, any other value will throw an error.
69 | Heavily inspired by setState from React's class components.
70 | This is very useful if you have many different values to update and don't want to have more than one .set(key, value, prop) lines.
71 |
72 | - observe(key, path) ⇒
*
73 | Returns an observable object. Modifying this object or any of its properties/indexes/children
74 | will automatically save those changes into enmap. This only works on
75 | objects and arrays, not "basic" values like strings or integers.
76 |
77 | - push(key, value, path, allowDupes)
78 | Push to an array value in Enmap.
79 |
80 | - math(key, operation, operand, path) ⇒
number
81 | Executes a mathematical operation on a value and saves it in the enmap.
82 |
83 | - inc(key, path) ⇒
number
84 | Increments a key's value or property by 1. Value must be a number, or a path to a number.
85 |
86 | - dec(key, path) ⇒
Enmap
87 | Decrements a key's value or property by 1. Value must be a number, or a path to a number.
88 |
89 | - ensure(key, defaultValue, path) ⇒
*
90 | Returns the key's value, or the default given, ensuring that the data is there.
91 | This is a shortcut to "if enmap doesn't have key, set it, then get it" which is a very common pattern.
92 |
93 | - includes(key, value, path) ⇒
boolean
94 | Performs Array.includes() on a certain enmap value. Works similar to
95 | Array.includes().
96 |
97 | - remove(key, val, path)
98 | Remove a value in an Array or Object element in Enmap. Note that this only works for
99 | values, not keys. Note that only one value is removed, no more. Arrays of objects must use a function to remove,
100 | as full object matching is not supported.
101 |
102 | - export() ⇒
string
103 | Exports the enmap data to stringified JSON format.
104 | WARNING: Does not work on memory enmaps containing complex data!
105 |
106 | - import(data, overwrite, clear)
107 | Import an existing json export from enmap. This data must have been exported from enmap,
108 | and must be from a version that's equivalent or lower than where you're importing it.
109 | (This means Enmap 5 data is compatible in Enmap 6).
110 |
111 | - multi(names, options) ⇒
Object
112 | Initialize multiple Enmaps easily.
113 |
114 | - random([count]) ⇒
* | Array.<*>
115 | Obtains random value(s) from this Enmap. This relies on Enmap#array.
116 |
117 | - randomKey([count]) ⇒
* | Array.<*>
118 | Obtains random key(s) from this Enmap. This relies on Enmap#keyArray
119 |
120 | - every(valueOrFunction, [path]) ⇒
boolean
121 | Similar to
122 | Array.every().
123 | Supports either a predicate function or a value to compare.
124 | Returns true only if the predicate function returns true for all elements in the array (or the value is strictly equal in all elements).
125 |
126 | - some(valueOrFunction, [path]) ⇒
Array
127 | Similar to
128 | Array.some().
129 | Supports either a predicate function or a value to compare.
130 | Returns true if the predicate function returns true for at least one element in the array (or the value is equal in at least one element).
131 |
132 | - map(pathOrFn) ⇒
Array
133 | Similar to
134 | Array.map().
135 | Returns an array of the results of applying the callback to all elements.
136 |
137 | - find(pathOrFn, [value]) ⇒
*
138 | Searches for a single item where its specified property's value is identical to the given value
139 | (item[prop] === value), or the given function returns a truthy value. In the latter case, this is similar to
140 | Array.find().
141 |
142 | - findIndex(pathOrFn, [value]) ⇒
string | number
143 | Searches for the key of a single item where its specified property's value is identical to the given value
144 | (item[prop] === value), or the given function returns a truthy value. In the latter case, this is similar to
145 | Array.findIndex().
146 |
147 | - reduce(predicate, [initialValue]) ⇒
*
148 | Similar to
149 | Array.reduce().
150 |
151 | - filter(pathOrFn, [value]) ⇒
Enmap
152 | Similar to
153 | Array.filter().
154 | Returns an array of values where the given function returns true for that value.
155 | Alternatively you can provide a value and path to filter by using exact value matching.
156 |
157 | - sweep(pathOrFn, [value]) ⇒
number
158 | Deletes entries that satisfy the provided filter function or value matching.
159 |
160 | - changed(cb)
161 | Function called whenever data changes within Enmap after the initial load.
162 | Can be used to detect if another part of your code changed a value in enmap and react on it.
163 |
164 | - partition(pathOrFn, value) ⇒
Array.<Array.<*>>
165 | Separates the Enmap into multiple arrays given a function that separates them.
166 |
167 |
168 |
169 |
170 |
171 | ## size ⇒ number
172 | Get the number of key/value pairs saved in the enmap.
173 |
174 | **Kind**: instance property of Enmap
175 | **Returns**: number - The number of elements in the enmap.
176 | **Read only**: true
177 |
178 |
179 | ## db ⇒ Database
180 | Get the better-sqlite3 database object. Useful if you want to directly query or interact with the
181 | underlying SQLite database. Use at your own risk, as errors here might cause loss of data or corruption!
182 |
183 | **Kind**: instance property of Enmap
184 |
185 |
186 | ## autonum ⇒ string
187 | Generates an automatic numerical key for inserting a new value.
188 | This is a "weak" method, it ensures the value isn't duplicated, but does not
189 | guarantee it's sequential (if a value is deleted, another can take its place).
190 | Useful for logging, actions, items, etc - anything that doesn't already have a unique ID.
191 |
192 | **Kind**: instance property of Enmap
193 | **Returns**: string - The generated key number.
194 | **Read only**: true
195 | **Example**
196 | ```js
197 | enmap.set(enmap.autonum, "This is a new value");
198 | ```
199 |
200 |
201 | ## set(key, value, path)
202 | Sets a value in Enmap. If the key already has a value, overwrites the data (or the value in a path, if provided).
203 |
204 | **Kind**: instance method of Enmap
205 |
206 | | Param | Description |
207 | | --- | --- |
208 | | key | Required. The location in which the data should be saved. |
209 | | value | Required. The value to write. Values must be serializable, which is done through (better-serialize)[https://github.com/RealShadowNova/better-serialize] If the value is not directly serializable, please use a custom serializer/deserializer. |
210 | | path | Optional. The path to the property to modify inside the value object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
211 |
212 | **Example**
213 | ```js
214 | // Direct Value Examples
215 | enmap.set('simplevalue', 'this is a string');
216 | enmap.set('isEnmapGreat', true);
217 | enmap.set('TheAnswer', 42);
218 | enmap.set('IhazObjects', { color: 'black', action: 'paint', desire: true });
219 | enmap.set('ArraysToo', [1, "two", "tree", "foor"])
220 |
221 | // Settings Properties
222 | enmap.set('IhazObjects', 'blue', 'color'); //modified previous object
223 | enmap.set('ArraysToo', 'three', 2); // changes "tree" to "three" in array.
224 | ```
225 |
226 |
227 | ## get(key, path) ⇒
228 | Retrieves a value from the enmap, using its key.
229 |
230 | **Kind**: instance method of Enmap
231 | **Returns**: The parsed value for this key.
232 |
233 | | Param | Description |
234 | | --- | --- |
235 | | key | The key to retrieve from the enmap. |
236 | | path | Optional. The property to retrieve from the object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
237 |
238 | **Example**
239 | ```js
240 | const myKeyValue = enmap.get("myKey");
241 | console.log(myKeyValue);
242 |
243 | const someSubValue = enmap.get("anObjectKey", "someprop.someOtherSubProp");
244 | ```
245 |
246 |
247 | ## has(key) ⇒ boolean
248 | Returns whether or not the key exists in the Enmap.
249 |
250 | **Kind**: instance method of Enmap
251 |
252 | | Param | Description |
253 | | --- | --- |
254 | | key | Required. The key of the element to add to The Enmap or array. |
255 |
256 | **Example**
257 | ```js
258 | if(enmap.has("myKey")) {
259 | // key is there
260 | }
261 | ```
262 |
263 |
264 | ## delete(key, path)
265 | Deletes a key in the Enmap.
266 |
267 | **Kind**: instance method of Enmap
268 |
269 | | Param | Description |
270 | | --- | --- |
271 | | key | Required. The key of the element to delete from The Enmap. |
272 | | path | Optional. The name of the property to remove from the object. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
273 |
274 |
275 |
276 | ## clear() ⇒ void
277 | Deletes everything from the enmap.
278 |
279 | **Kind**: instance method of Enmap
280 |
281 |
282 | ## keys() ⇒ Array.<string>
283 | Get all the keys of the enmap as an array.
284 |
285 | **Kind**: instance method of Enmap
286 | **Returns**: Array.<string> - An array of all the keys in the enmap.
287 |
288 |
289 | ## values() ⇒ Array.<\*>
290 | Get all the values of the enmap as an array.
291 |
292 | **Kind**: instance method of Enmap
293 | **Returns**: Array.<\*> - An array of all the values in the enmap.
294 |
295 |
296 | ## entries() ⇒ Array.<Array.<\*, \*>>
297 | Get all entries of the enmap as an array, with each item containing the key and value.
298 |
299 | **Kind**: instance method of Enmap
300 | **Returns**: Array.<Array.<\*, \*>> - An array of arrays, with each sub-array containing two items, the key and the value.
301 |
302 |
303 | ## update(key, valueOrFunction) ⇒ \*
304 | Update an existing object value in Enmap by merging new keys. **This only works on objects**, any other value will throw an error.
305 | Heavily inspired by setState from React's class components.
306 | This is very useful if you have many different values to update and don't want to have more than one .set(key, value, prop) lines.
307 |
308 | **Kind**: instance method of Enmap
309 | **Returns**: \* - The modified (merged) value.
310 |
311 | | Param | Type | Description |
312 | | --- | --- | --- |
313 | | key | string | The key of the object to update. |
314 | | valueOrFunction | \* | Either an object to merge with the existing value, or a function that provides the existing object and expects a new object as a return value. In the case of a straight value, the merge is recursive and will add any missing level. If using a function, it is your responsibility to merge the objects together correctly. |
315 |
316 | **Example**
317 | ```js
318 | // Define an object we're going to update
319 | enmap.set("obj", { a: 1, b: 2, c: 3 });
320 |
321 | // Direct merge
322 | enmap.update("obj", { d: 4, e: 5 });
323 | // obj is now { a: 1, b: 2, c: 3, d: 4, e: 5 }
324 |
325 | // Functional update
326 | enmap.update("obj", (previous) => ({
327 | ...obj,
328 | f: 6,
329 | g: 7
330 | }));
331 | // this example takes heavy advantage of the spread operators.
332 | // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
333 | ```
334 |
335 |
336 | ## observe(key, path) ⇒ \*
337 | Returns an observable object. Modifying this object or any of its properties/indexes/children
338 | will automatically save those changes into enmap. This only works on
339 | objects and arrays, not "basic" values like strings or integers.
340 |
341 | **Kind**: instance method of Enmap
342 | **Returns**: \* - The value for this key.
343 |
344 | | Param | Type | Description |
345 | | --- | --- | --- |
346 | | key | \* | The key to retrieve from the enmap. |
347 | | path | string | Optional. The property to retrieve from the object or array. |
348 |
349 |
350 |
351 | ## push(key, value, path, allowDupes)
352 | Push to an array value in Enmap.
353 |
354 | **Kind**: instance method of Enmap
355 |
356 | | Param | Type | Default | Description |
357 | | --- | --- | --- | --- |
358 | | key | string | | Required. The key of the array element to push to in Enmap. |
359 | | value | \* | | Required. The value to push to the array. |
360 | | path | string | | Optional. The path to the property to modify inside the value object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
361 | | allowDupes | boolean | false | Optional. Allow duplicate values in the array (default: false). |
362 |
363 | **Example**
364 | ```js
365 | // Assuming
366 | enmap.set("simpleArray", [1, 2, 3, 4]);
367 | enmap.set("arrayInObject", {sub: [1, 2, 3, 4]});
368 |
369 | enmap.push("simpleArray", 5); // adds 5 at the end of the array
370 | enmap.push("arrayInObject", "five", "sub"); // adds "five" at the end of the sub array
371 | ```
372 |
373 |
374 | ## math(key, operation, operand, path) ⇒ number
375 | Executes a mathematical operation on a value and saves it in the enmap.
376 |
377 | **Kind**: instance method of Enmap
378 | **Returns**: number - The updated value after the operation
379 |
380 | | Param | Type | Description |
381 | | --- | --- | --- |
382 | | key | string | The enmap key on which to execute the math operation. |
383 | | operation | string | Which mathematical operation to execute. Supports most math ops: =, -, *, /, %, ^, and english spelling of those operations. |
384 | | operand | number | The right operand of the operation. |
385 | | path | string | Optional. The property path to execute the operation on, if the value is an object or array. |
386 |
387 | **Example**
388 | ```js
389 | // Assuming
390 | points.set("number", 42);
391 | points.set("numberInObject", {sub: { anInt: 5 }});
392 |
393 | points.math("number", "/", 2); // 21
394 | points.math("number", "add", 5); // 26
395 | points.math("number", "modulo", 3); // 2
396 | points.math("numberInObject", "+", 10, "sub.anInt");
397 | ```
398 |
399 |
400 | ## inc(key, path) ⇒ number
401 | Increments a key's value or property by 1. Value must be a number, or a path to a number.
402 |
403 | **Kind**: instance method of Enmap
404 | **Returns**: number - The udpated value after incrementing.
405 |
406 | | Param | Type | Description |
407 | | --- | --- | --- |
408 | | key | string | The enmap key where the value to increment is stored. |
409 | | path | string | Optional. The property path to increment, if the value is an object or array. |
410 |
411 | **Example**
412 | ```js
413 | // Assuming
414 | points.set("number", 42);
415 | points.set("numberInObject", {sub: { anInt: 5 }});
416 |
417 | points.inc("number"); // 43
418 | points.inc("numberInObject", "sub.anInt"); // {sub: { anInt: 6 }}
419 | ```
420 |
421 |
422 | ## dec(key, path) ⇒ Enmap
423 | Decrements a key's value or property by 1. Value must be a number, or a path to a number.
424 |
425 | **Kind**: instance method of Enmap
426 | **Returns**: Enmap - The enmap.
427 |
428 | | Param | Type | Description |
429 | | --- | --- | --- |
430 | | key | string | The enmap key where the value to decrement is stored. |
431 | | path | string | Optional. The property path to decrement, if the value is an object or array. |
432 |
433 | **Example**
434 | ```js
435 | // Assuming
436 | points.set("number", 42);
437 | points.set("numberInObject", {sub: { anInt: 5 }});
438 |
439 | points.dec("number"); // 41
440 | points.dec("numberInObject", "sub.anInt"); // {sub: { anInt: 4 }}
441 | ```
442 |
443 |
444 | ## ensure(key, defaultValue, path) ⇒ \*
445 | Returns the key's value, or the default given, ensuring that the data is there.
446 | This is a shortcut to "if enmap doesn't have key, set it, then get it" which is a very common pattern.
447 |
448 | **Kind**: instance method of Enmap
449 | **Returns**: \* - The value from the database for the key, or the default value provided for a new key.
450 |
451 | | Param | Type | Description |
452 | | --- | --- | --- |
453 | | key | string | Required. The key you want to make sure exists. |
454 | | defaultValue | \* | Required. The value you want to save in the database and return as default. |
455 | | path | string | Optional. If presents, ensures both the key exists as an object, and the full path exists. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
456 |
457 | **Example**
458 | ```js
459 | // Simply ensure the data exists (for using property methods):
460 | enmap.ensure("mykey", {some: "value", here: "as an example"});
461 | enmap.has("mykey"); // always returns true
462 | enmap.get("mykey", "here") // returns "as an example";
463 |
464 | // Get the default value back in a variable:
465 | const settings = mySettings.ensure("1234567890", defaultSettings);
466 | console.log(settings) // enmap's value for "1234567890" if it exists, otherwise the defaultSettings value.
467 | ```
468 |
469 |
470 | ## includes(key, value, path) ⇒ boolean
471 | Performs Array.includes() on a certain enmap value. Works similar to
472 | [Array.includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes).
473 |
474 | **Kind**: instance method of Enmap
475 | **Returns**: boolean - Whether the array contains the value.
476 |
477 | | Param | Type | Description |
478 | | --- | --- | --- |
479 | | key | string | Required. The key of the array to check the value of. |
480 | | value | string \| number | Required. The value to check whether it's in the array. |
481 | | path | string | Optional. The property to access the array inside the value object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" |
482 |
483 |
484 |
485 | ## remove(key, val, path)
486 | Remove a value in an Array or Object element in Enmap. Note that this only works for
487 | values, not keys. Note that only one value is removed, no more. Arrays of objects must use a function to remove,
488 | as full object matching is not supported.
489 |
490 | **Kind**: instance method of Enmap
491 |
492 | | Param | Type | Description |
493 | | --- | --- | --- |
494 | | key | string | Required. The key of the element to remove from in Enmap. |
495 | | val | \* \| function | Required. The value to remove from the array or object. OR a function to match an object. If using a function, the function provides the object value and must return a boolean that's true for the object you want to remove. |
496 | | path | string | Optional. The name of the array property to remove from. Should be a path with dot notation, such as "prop1.subprop2.subprop3". If not presents, removes directly from the value. |
497 |
498 | **Example**
499 | ```js
500 | // Assuming
501 | enmap.set('array', [1, 2, 3])
502 | enmap.set('objectarray', [{ a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 }])
503 |
504 | enmap.remove('array', 1); // value is now [2, 3]
505 | enmap.remove('objectarray', (value) => value.e === 5); // value is now [{ a: 1, b: 2, c: 3 }]
506 | ```
507 |
508 |
509 | ## export() ⇒ string
510 | Exports the enmap data to stringified JSON format.
511 | **__WARNING__**: Does not work on memory enmaps containing complex data!
512 |
513 | **Kind**: instance method of Enmap
514 | **Returns**: string - The enmap data in a stringified JSON format.
515 |
516 |
517 | ## import(data, overwrite, clear)
518 | Import an existing json export from enmap. This data must have been exported from enmap,
519 | and must be from a version that's equivalent or lower than where you're importing it.
520 | (This means Enmap 5 data is compatible in Enmap 6).
521 |
522 | **Kind**: instance method of Enmap
523 |
524 | | Param | Type | Default | Description |
525 | | --- | --- | --- | --- |
526 | | data | string | | The data to import to Enmap. Must contain all the required fields provided by an enmap export(). |
527 | | overwrite | boolean | true | Defaults to `true`. Whether to overwrite existing key/value data with incoming imported data |
528 | | clear | boolean | false | Defaults to `false`. Whether to clear the enmap of all data before importing (**__WARNING__**: Any existing data will be lost! This cannot be undone.) |
529 |
530 |
531 |
532 | ## multi(names, options) ⇒ Object
533 | Initialize multiple Enmaps easily.
534 |
535 | **Kind**: instance method of Enmap
536 | **Returns**: Object - An array of initialized Enmaps.
537 |
538 | | Param | Type | Description |
539 | | --- | --- | --- |
540 | | names | Array.<string> | Array of strings. Each array entry will create a separate enmap with that name. |
541 | | options | Object | Options object to pass to each enmap, excluding the name.. |
542 |
543 | **Example**
544 | ```js
545 | // Using local variables.
546 | const Enmap = require('enmap');
547 | const { settings, tags, blacklist } = Enmap.multi(['settings', 'tags', 'blacklist']);
548 |
549 | // Attaching to an existing object (for instance some API's client)
550 | import Enmap from 'enmap';
551 | Object.assign(client, Enmap.multi(["settings", "tags", "blacklist"]));
552 | ```
553 |
554 |
555 | ## random([count]) ⇒ \* \| Array.<\*>
556 | Obtains random value(s) from this Enmap. This relies on [Enmap#array](Enmap#array).
557 |
558 | **Kind**: instance method of Enmap
559 | **Returns**: \* \| Array.<\*> - The single value if `count` is undefined,
560 | or an array of values of `count` length
561 |
562 | | Param | Type | Default | Description |
563 | | --- | --- | --- | --- |
564 | | [count] | number | 1 | Number of values to obtain randomly |
565 |
566 |
567 |
568 | ## randomKey([count]) ⇒ \* \| Array.<\*>
569 | Obtains random key(s) from this Enmap. This relies on [Enmap#keyArray](Enmap#keyArray)
570 |
571 | **Kind**: instance method of Enmap
572 | **Returns**: \* \| Array.<\*> - The single key if `count` is undefined,
573 | or an array of keys of `count` length
574 |
575 | | Param | Type | Default | Description |
576 | | --- | --- | --- | --- |
577 | | [count] | number | 1 | Number of keys to obtain randomly |
578 |
579 |
580 |
581 | ## every(valueOrFunction, [path]) ⇒ boolean
582 | Similar to
583 | [Array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every).
584 | Supports either a predicate function or a value to compare.
585 | Returns true only if the predicate function returns true for all elements in the array (or the value is strictly equal in all elements).
586 |
587 | **Kind**: instance method of Enmap
588 |
589 | | Param | Type | Description |
590 | | --- | --- | --- |
591 | | valueOrFunction | function \| string | Function used to test (should return a boolean), or a value to compare. |
592 | | [path] | string | Required if the value is an object. The path to the property to compare with. |
593 |
594 |
595 |
596 | ## some(valueOrFunction, [path]) ⇒ Array
597 | Similar to
598 | [Array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some).
599 | Supports either a predicate function or a value to compare.
600 | Returns true if the predicate function returns true for at least one element in the array (or the value is equal in at least one element).
601 |
602 | **Kind**: instance method of Enmap
603 |
604 | | Param | Type | Description |
605 | | --- | --- | --- |
606 | | valueOrFunction | function \| string | Function used to test (should return a boolean), or a value to compare. |
607 | | [path] | string | Required if the value is an object. The path to the property to compare with. |
608 |
609 |
610 |
611 | ## map(pathOrFn) ⇒ Array
612 | Similar to
613 | [Array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).
614 | Returns an array of the results of applying the callback to all elements.
615 |
616 | **Kind**: instance method of Enmap
617 |
618 | | Param | Type | Description |
619 | | --- | --- | --- |
620 | | pathOrFn | function \| string | A function that produces an element of the new Array, or a path to the property to map. |
621 |
622 |
623 |
624 | ## find(pathOrFn, [value]) ⇒ \*
625 | Searches for a single item where its specified property's value is identical to the given value
626 | (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is similar to
627 | [Array.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
628 |
629 | **Kind**: instance method of Enmap
630 |
631 | | Param | Type | Description |
632 | | --- | --- | --- |
633 | | pathOrFn | string \| function | The path to the value to test against, or the function to test with |
634 | | [value] | \* | The expected value - only applicable and required if using a property for the first argument |
635 |
636 | **Example**
637 | ```js
638 | enmap.find('username', 'Bob');
639 | ```
640 | **Example**
641 | ```js
642 | enmap.find(val => val.username === 'Bob');
643 | ```
644 |
645 |
646 | ## findIndex(pathOrFn, [value]) ⇒ string \| number
647 | Searches for the key of a single item where its specified property's value is identical to the given value
648 | (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is similar to
649 | [Array.findIndex()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex).
650 |
651 | **Kind**: instance method of Enmap
652 |
653 | | Param | Type | Description |
654 | | --- | --- | --- |
655 | | pathOrFn | string \| function | The path to the value to test against, or the function to test with |
656 | | [value] | \* | The expected value - only applicable and required if using a property for the first argument |
657 |
658 | **Example**
659 | ```js
660 | enmap.findIndex('username', 'Bob');
661 | ```
662 | **Example**
663 | ```js
664 | enmap.findIndex(val => val.username === 'Bob');
665 | ```
666 |
667 |
668 | ## reduce(predicate, [initialValue]) ⇒ \*
669 | Similar to
670 | [Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).
671 |
672 | **Kind**: instance method of Enmap
673 |
674 | | Param | Type | Description |
675 | | --- | --- | --- |
676 | | predicate | function | Function used to reduce, taking three arguments; `accumulator`, `currentValue`, `currentKey`. |
677 | | [initialValue] | \* | Starting value for the accumulator |
678 |
679 |
680 |
681 | ## filter(pathOrFn, [value]) ⇒ Enmap
682 | Similar to
683 | [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).
684 | Returns an array of values where the given function returns true for that value.
685 | Alternatively you can provide a value and path to filter by using exact value matching.
686 |
687 | **Kind**: instance method of Enmap
688 |
689 | | Param | Type | Description |
690 | | --- | --- | --- |
691 | | pathOrFn | function | The path to the value to test against, or the function to test with. If using a function, this function should return a boolean. |
692 | | [value] | string | Value to use as `this` when executing function |
693 |
694 |
695 |
696 | ## sweep(pathOrFn, [value]) ⇒ number
697 | Deletes entries that satisfy the provided filter function or value matching.
698 |
699 | **Kind**: instance method of Enmap
700 | **Returns**: number - The number of removed entries.
701 |
702 | | Param | Type | Description |
703 | | --- | --- | --- |
704 | | pathOrFn | function \| string | The path to the value to test against, or the function to test with. |
705 | | [value] | \* | The expected value - only applicable and required if using a property for the first argument. |
706 |
707 |
708 |
709 | ## changed(cb)
710 | Function called whenever data changes within Enmap after the initial load.
711 | Can be used to detect if another part of your code changed a value in enmap and react on it.
712 |
713 | **Kind**: instance method of Enmap
714 |
715 | | Param | Type | Description |
716 | | --- | --- | --- |
717 | | cb | function | A callback function that will be called whenever data changes in the enmap. |
718 |
719 | **Example**
720 | ```js
721 | enmap.changed((keyName, oldValue, newValue) => {
722 | console.log(`Value of ${keyName} has changed from: \n${oldValue}\nto\n${newValue}`);
723 | });
724 | ```
725 |
726 |
727 | ## partition(pathOrFn, value) ⇒ Array.<Array.<\*>>
728 | Separates the Enmap into multiple arrays given a function that separates them.
729 |
730 | **Kind**: instance method of Enmap
731 | **Returns**: Array.<Array.<\*>> - An array of arrays with the partitioned data.
732 |
733 | | Param | Type | Description |
734 | | --- | --- | --- |
735 | | pathOrFn | \* | the path to the value to test against, or the function to test with. |
736 | | value | \* | the value to use as a condition for partitioning. |
737 |
738 |
--------------------------------------------------------------------------------