diff --git a/docs/api.md b/docs/api.md index b04566c..6df770f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -15,28 +15,42 @@ If you're doing a PR on the docs github, please do not manually edit the below c ### new Enmap([options]) + Initializes a new Enmap, with options. +| Param | Type | Description | +| ----------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [options] | Object | Options for the enmap. See https://enmap.evie.dev/usage#enmap-options for details. | +| [options.name] | string | The name of the enmap. Represents its table name in sqlite. Unless inMemory is set to true, the enmap will be persisted to disk. | +| [options.dataDir] | string | Defaults to `./data`. Determines where the sqlite files will be stored. Can be relative (to your project root) or absolute on the disk. Windows users , remember to escape your backslashes! _Note_: Enmap will not automatically create the folder if it is set manually, so make sure it exists before starting your code! | +| [options.ensureProps] | boolean | defaults to `true`. If enabled and the value in the enmap is an object, using ensure() will also ensure that every property present in the default object will be added to the value, if it's absent. See ensure API reference for more information. | +| [options.autoEnsure] | \* | default is disabled. When provided a value, essentially runs ensure(key, autoEnsure) automatically so you don't have to. This is especially useful on get(), but will also apply on set(), and any array and object methods that interact with the database. | +| [options.serializer] | function | Optional. If a function is provided, it will execute on the data when it is written to the database. This is generally used to convert the value into a format that can be saved in the database, such as converting a complete class instance to just its ID. This function may return the value to be saved, or a promise that resolves to that value (in other words, can be an async function). | +| [options.deserializer] | function | Optional. If a function is provided, it will execute on the data when it is read from the database. This is generally used to convert the value from a stored ID into a more complex object. This function may return a value, or a promise that resolves to that value (in other words, can be an async function). | +| [options.inMemory] | boolean | Optional. If set to true, the enmap will be in-memory only, and will not write to disk. Useful for temporary stores. | +| [options.sqliteOptions] | Object | Optional. An object of options to pass to the better-sqlite3 Database constructor. | -| Param | Type | Description | -| --- | --- | --- | -| [options] | Object | Options for the enmap. See https://enmap.evie.codes/usage#enmap-options for details. | -| [options.name] | string | The name of the enmap. Represents its table name in sqlite. Unless inMemory is set to true, the enmap will be persisted to disk. | -| [options.dataDir] | string | Defaults to `./data`. Determines where the sqlite files will be stored. Can be relative (to your project root) or absolute on the disk. Windows users , remember to escape your backslashes! *Note*: Enmap will not automatically create the folder if it is set manually, so make sure it exists before starting your code! | -| [options.ensureProps] | boolean | defaults to `true`. If enabled and the value in the enmap is an object, using ensure() will also ensure that every property present in the default object will be added to the value, if it's absent. See ensure API reference for more information. | -| [options.autoEnsure] | \* | default is disabled. When provided a value, essentially runs ensure(key, autoEnsure) automatically so you don't have to. This is especially useful on get(), but will also apply on set(), and any array and object methods that interact with the database. | -| [options.serializer] | function | Optional. If a function is provided, it will execute on the data when it is written to the database. This is generally used to convert the value into a format that can be saved in the database, such as converting a complete class instance to just its ID. This function may return the value to be saved, or a promise that resolves to that value (in other words, can be an async function). | -| [options.deserializer] | function | Optional. If a function is provided, it will execute on the data when it is read from the database. This is generally used to convert the value from a stored ID into a more complex object. This function may return a value, or a promise that resolves to that value (in other words, can be an async function). | -| [options.inMemory] | boolean | Optional. If set to true, the enmap will be in-memory only, and will not write to disk. Useful for temporary stores. | -| [options.sqliteOptions] | Object | Optional. An object of options to pass to the better-sqlite3 Database constructor. | +**Example** -**Example** ```js -const Enmap = require("enmap"); // Named, Persistent enmap const myEnmap = new Enmap({ name: "testing" }); // Memory-only enmap const memoryEnmap = new Enmap({ inMemory: true }); // Enmap that automatically assigns a default object when getting or setting anything. const autoEnmap = new Enmap({name: "settings", autoEnsure: { setting1: false, message: "default message"}}) +const Enmap = require('enmap'); +// Named, Persistent enmap +const myEnmap = new Enmap({ name: 'testing' }); + +// Memory-only enmap +const memoryEnmap = new Enmap({ inMemory: true }); + +// Enmap that automatically assigns a default object when getting or setting anything. +const autoEnmap = new Enmap({ + name: 'settings', + autoEnsure: { setting1: false, message: 'default message' }, +}); ``` + ### enmap.size ⇒ number + Get the number of key/value pairs saved in the enmap. **Kind**: instance property of Enmap @@ -45,88 +59,137 @@ Get the number of key/value pairs saved in the enmap. ### enmap.db ⇒ Database -Get the better-sqlite3 database object. Useful if you want to directly query or interact with the underlying SQLite database. Use at your own risk, as errors here might cause loss of data or corruption! + +Get the better-sqlite3 database object. Useful if you want to directly query or interact with the +underlying SQLite database. Use at your own risk, as errors here might cause loss of data or corruption! **Kind**: instance property of Enmap ### enmap.autonum ⇒ number -Generates an automatic numerical key for inserting a new value. This is a "weak" method, it ensures the value isn't duplicated, but does not guarantee it's sequential (if a value is deleted, another can take its place). Useful for logging, actions, items, etc - anything that doesn't already have a unique ID. + +Generates an automatic numerical key for inserting a new value. +This is a "weak" method, it ensures the value isn't duplicated, but does not +guarantee it's sequential (if a value is deleted, another can take its place). +Useful for logging, actions, items, etc - anything that doesn't already have a unique ID. **Kind**: instance property of Enmap **Returns**: number - The generated key number. **Read only**: true -**Example** +**Example** + ```js -enmap.set(enmap.autonum, "This is a new value"); +enmap.set(enmap.autonum, 'This is a new value'); ``` + ### enmap.set(key, value, path) + Sets a value in Enmap. If the key already has a value, overwrites the data (or the value in a path, if provided). -**Kind**: instance method of Enmap +**Kind**: instance method of Enmap -| Param | Type | Description | -| --- | --- | --- | -| key | string | Required. The location in which the data should be saved. | -| 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. | -| 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" | +| Param | Type | Description | +| ----- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| key | string | Required. The location in which the data should be saved. | +| 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. | +| 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" | + +**Example** -**Example** ```js -// Direct Value Examples enmap.set('simplevalue', 'this is a string'); enmap.set('isEnmapGreat', true); enmap.set('TheAnswer', 42); enmap.set('IhazObjects', { color: 'black', action: 'paint', desire: true }); enmap.set('ArraysToo', [1, "two", "tree", "foor"]) // Settings Properties enmap.set('IhazObjects', 'blue', 'color'); //modified previous object enmap.set('ArraysToo', 'three', 2); // changes "tree" to "three" in array. +// Direct Value Examples +enmap.set('simplevalue', 'this is a string'); +enmap.set('isEnmapGreat', true); +enmap.set('TheAnswer', 42); +enmap.set('IhazObjects', { color: 'black', action: 'paint', desire: true }); +enmap.set('ArraysToo', [1, 'two', 'tree', 'foor']); + +// Settings Properties +enmap.set('IhazObjects', 'blue', 'color'); //modified previous object +enmap.set('ArraysToo', 'three', 2); // changes "tree" to "three" in array. ``` + ### enmap.update(key, valueOrFunction) ⇒ \* -Update an existing object value in Enmap by merging new keys. **This only works on objects**, any other value will throw an error. Heavily inspired by setState from React's class components. 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. + +Update an existing object value in Enmap by merging new keys. **This only works on objects**, any other value will throw an error. +Heavily inspired by setState from React's class components. +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. **Kind**: instance method of Enmap -**Returns**: \* - The modified (merged) value. +**Returns**: \* - The modified (merged) value. -| Param | Type | Description | -| --- | --- | --- | -| key | string | The key of the object to update. | -| 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. | +| Param | Type | Description | +| --------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| key | string | The key of the object to update. | +| 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. | + +**Example** -**Example** ```js -// Define an object we're going to update enmap.set("obj", { a: 1, b: 2, c: 3 }); // Direct merge enmap.update("obj", { d: 4, e: 5 }); // obj is now { a: 1, b: 2, c: 3, d: 4, e: 5 } // Functional update enmap.update("obj", (previous) => ({ ...obj, f: 6, g: 7 })); // this example takes heavy advantage of the spread operators. // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax +// Define an object we're going to update +enmap.set('obj', { a: 1, b: 2, c: 3 }); + +// Direct merge +enmap.update('obj', { d: 4, e: 5 }); +// obj is now { a: 1, b: 2, c: 3, d: 4, e: 5 } + +// Functional update +enmap.update('obj', (previous) => ({ + ...obj, + f: 6, + g: 7, +})); +// this example takes heavy advantage of the spread operators. +// More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax ``` + ### enmap.get(key, path) ⇒ \* + Retrieves a value from the enmap, using its key. **Kind**: instance method of Enmap -**Returns**: \* - The parsed value for this key. +**Returns**: \* - The parsed value for this key. -| Param | Type | Description | -| --- | --- | --- | -| key | string | The key to retrieve from the enmap. | -| path | string | Optional. The property to retrieve from the object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" | +| Param | Type | Description | +| ----- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| key | string | The key to retrieve from the enmap. | +| path | string | Optional. The property to retrieve from the object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" | + +**Example** -**Example** ```js -const myKeyValue = enmap.get("myKey"); console.log(myKeyValue); const someSubValue = enmap.get("anObjectKey", "someprop.someOtherSubProp"); +const myKeyValue = enmap.get('myKey'); +console.log(myKeyValue); + +const someSubValue = enmap.get('anObjectKey', 'someprop.someOtherSubProp'); ``` + ### enmap.observe(key, path) ⇒ \* -Returns an observable object. Modifying this object or any of its properties/indexes/children will automatically save those changes into enmap. This only works on objects and arrays, not "basic" values like strings or integers. + +Returns an observable object. Modifying this object or any of its properties/indexes/children +will automatically save those changes into enmap. This only works on +objects and arrays, not "basic" values like strings or integers. **Kind**: instance method of Enmap -**Returns**: \* - The value for this key. +**Returns**: \* - The value for this key. -| Param | Type | Description | -| --- | --- | --- | -| key | \* | The key to retrieve from the enmap. | -| path | string | Optional. The property to retrieve from the object or array. | +| Param | Type | Description | +| ----- | ------------------- | ------------------------------------------------------------ | +| key | \* | The key to retrieve from the enmap. | +| path | string | Optional. The property to retrieve from the object or array. | ### enmap.keys() ⇒ Array.<string> + Get all the keys of the enmap as an array. **Kind**: instance method of Enmap @@ -134,6 +197,7 @@ Get all the keys of the enmap as an array. ### enmap.values() ⇒ Array.<\*> + Get all the values of the enmap as an array. **Kind**: instance method of Enmap @@ -141,6 +205,7 @@ Get all the values of the enmap as an array. ### enmap.entries() ⇒ Array.<Array.<\*, \*>> + Get all entries of the enmap as an array, with each item containing the key and value. **Kind**: instance method of Enmap @@ -148,355 +213,485 @@ Get all entries of the enmap as an array, with each item containing the key and ### enmap.push(key, value, path, allowDupes) + Push to an array value in Enmap. -**Kind**: instance method of Enmap +**Kind**: instance method of Enmap + +| Param | Type | Default | Description | +| ---------- | -------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| key | string | | Required. The key of the array element to push to in Enmap. | +| value | \* | | Required. The value to push to the array. | +| 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" | +| allowDupes | boolean | false | Optional. Allow duplicate values in the array (default: false). | -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| key | string | | Required. The key of the array element to push to in Enmap. | -| value | \* | | Required. The value to push to the array. | -| 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" | -| allowDupes | boolean | false | Optional. Allow duplicate values in the array (default: false). | +**Example** -**Example** ```js -// Assuming enmap.set("simpleArray", [1, 2, 3, 4]); enmap.set("arrayInObject", {sub: [1, 2, 3, 4]}); enmap.push("simpleArray", 5); // adds 5 at the end of the array enmap.push("arrayInObject", "five", "sub"); // adds "five" at the end of the sub array +// Assuming +enmap.set('simpleArray', [1, 2, 3, 4]); +enmap.set('arrayInObject', { sub: [1, 2, 3, 4] }); + +enmap.push('simpleArray', 5); // adds 5 at the end of the array +enmap.push('arrayInObject', 'five', 'sub'); // adds "five" at the end of the sub array ``` + ### enmap.math(key, operation, operand, path) ⇒ number + Executes a mathematical operation on a value and saves it in the enmap. **Kind**: instance method of Enmap -**Returns**: number - The updated value after the operation +**Returns**: number - The updated value after the operation + +| Param | Type | Description | +| --------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| key | string | The enmap key on which to execute the math operation. | +| operation | string | Which mathematical operation to execute. Supports most math ops: =, -, \*, /, %, ^, and english spelling of those operations. | +| operand | number | The right operand of the operation. | +| path | string | Optional. The property path to execute the operation on, if the value is an object or array. | -| Param | Type | Description | -| --- | --- | --- | -| key | string | The enmap key on which to execute the math operation. | -| operation | string | Which mathematical operation to execute. Supports most math ops: =, -, *, /, %, ^, and english spelling of those operations. | -| operand | number | The right operand of the operation. | -| path | string | Optional. The property path to execute the operation on, if the value is an object or array. | +**Example** -**Example** ```js -// Assuming points.set("number", 42); points.set("numberInObject", {sub: { anInt: 5 }}); points.math("number", "/", 2); // 21 points.math("number", "add", 5); // 26 points.math("number", "modulo", 3); // 2 points.math("numberInObject", "+", 10, "sub.anInt"); +// Assuming +points.set('number', 42); +points.set('numberInObject', { sub: { anInt: 5 } }); + +points.math('number', '/', 2); // 21 +points.math('number', 'add', 5); // 26 +points.math('number', 'modulo', 3); // 2 +points.math('numberInObject', '+', 10, 'sub.anInt'); ``` + ### enmap.inc(key, path) ⇒ number + Increments a key's value or property by 1. Value must be a number, or a path to a number. **Kind**: instance method of Enmap -**Returns**: number - The udpated value after incrementing. +**Returns**: number - The udpated value after incrementing. + +| Param | Type | Description | +| ----- | ------------------- | ----------------------------------------------------------------------------- | +| key | string | The enmap key where the value to increment is stored. | +| path | string | Optional. The property path to increment, if the value is an object or array. | -| Param | Type | Description | -| --- | --- | --- | -| key | string | The enmap key where the value to increment is stored. | -| path | string | Optional. The property path to increment, if the value is an object or array. | +**Example** -**Example** ```js -// Assuming points.set("number", 42); points.set("numberInObject", {sub: { anInt: 5 }}); points.inc("number"); // 43 points.inc("numberInObject", "sub.anInt"); // {sub: { anInt: 6 }} +// Assuming +points.set('number', 42); +points.set('numberInObject', { sub: { anInt: 5 } }); + +points.inc('number'); // 43 +points.inc('numberInObject', 'sub.anInt'); // {sub: { anInt: 6 }} ``` + ### enmap.dec(key, path) ⇒ Enmap + Decrements a key's value or property by 1. Value must be a number, or a path to a number. **Kind**: instance method of Enmap -**Returns**: Enmap - The enmap. +**Returns**: Enmap - The enmap. + +| Param | Type | Description | +| ----- | ------------------- | ----------------------------------------------------------------------------- | +| key | string | The enmap key where the value to decrement is stored. | +| path | string | Optional. The property path to decrement, if the value is an object or array. | -| Param | Type | Description | -| --- | --- | --- | -| key | string | The enmap key where the value to decrement is stored. | -| path | string | Optional. The property path to decrement, if the value is an object or array. | +**Example** -**Example** ```js -// Assuming points.set("number", 42); points.set("numberInObject", {sub: { anInt: 5 }}); points.dec("number"); // 41 points.dec("numberInObject", "sub.anInt"); // {sub: { anInt: 4 }} +// Assuming +points.set('number', 42); +points.set('numberInObject', { sub: { anInt: 5 } }); + +points.dec('number'); // 41 +points.dec('numberInObject', 'sub.anInt'); // {sub: { anInt: 4 }} ``` + ### enmap.ensure(key, defaultValue, path) ⇒ \* -Returns the key's value, or the default given, ensuring that the data is there. This is a shortcut to "if enmap doesn't have key, set it, then get it" which is a very common pattern. + +Returns the key's value, or the default given, ensuring that the data is there. +This is a shortcut to "if enmap doesn't have key, set it, then get it" which is a very common pattern. **Kind**: instance method of Enmap -**Returns**: \* - The value from the database for the key, or the default value provided for a new key. +**Returns**: \* - The value from the database for the key, or the default value provided for a new key. + +| Param | Type | Description | +| ------------ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| key | string | Required. The key you want to make sure exists. | +| defaultValue | \* | Required. The value you want to save in the database and return as default. | +| 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" | -| Param | Type | Description | -| --- | --- | --- | -| key | string | Required. The key you want to make sure exists. | -| defaultValue | \* | Required. The value you want to save in the database and return as default. | -| 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" | +**Example** -**Example** ```js -// Simply ensure the data exists (for using property methods): enmap.ensure("mykey", {some: "value", here: "as an example"}); enmap.has("mykey"); // always returns true enmap.get("mykey", "here") // returns "as an example"; // Get the default value back in a variable: const settings = mySettings.ensure("1234567890", defaultSettings); console.log(settings) // enmap's value for "1234567890" if it exists, otherwise the defaultSettings value. +// Simply ensure the data exists (for using property methods): +enmap.ensure('mykey', { some: 'value', here: 'as an example' }); +enmap.has('mykey'); // always returns true +enmap.get('mykey', 'here'); // returns "as an example"; + +// Get the default value back in a variable: +const settings = mySettings.ensure('1234567890', defaultSettings); +console.log(settings); // enmap's value for "1234567890" if it exists, otherwise the defaultSettings value. ``` + ### enmap.has(key, path) ⇒ boolean + Returns whether or not the key exists in the Enmap. -**Kind**: instance method of Enmap +**Kind**: instance method of Enmap -| Param | Type | Description | -| --- | --- | --- | -| key | string | Required. The key of the element to add to The Enmap or array. | -| path | string | Optional. The property to verify inside the value object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" | +| Param | Type | Description | +| ----- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| key | string | Required. The key of the element to add to The Enmap or array. | +| path | string | Optional. The property to verify inside the value object or array. Should be a path with dot notation, such as "prop1.subprop2.subprop3" | + +**Example** -**Example** ```js -if(enmap.has("myKey")) { // key is there } if(!enmap.has("myOtherKey", "oneProp.otherProp.SubProp")) return false; +if (enmap.has('myKey')) { + // key is there +} + +if (!enmap.has('myOtherKey', 'oneProp.otherProp.SubProp')) return false; ``` + ### enmap.includes(key, value, path) ⇒ boolean -Performs Array.includes() on a certain enmap value. Works similar to [Array.includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes). + +Performs Array.includes() on a certain enmap value. Works similar to +[Array.includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes). **Kind**: instance method of Enmap -**Returns**: boolean - Whether the array contains the value. +**Returns**: boolean - Whether the array contains the value. -| Param | Type | Description | -| --- | --- | --- | -| key | string | Required. The key of the array to check the value of. | -| value | string \| number | Required. The value to check whether it's in the array. | -| 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" | +| Param | Type | Description | +| ----- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| key | string | Required. The key of the array to check the value of. | +| value | string \| number | Required. The value to check whether it's in the array. | +| 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" | ### enmap.delete(key, path) + Deletes a key in the Enmap. -**Kind**: instance method of Enmap +**Kind**: instance method of Enmap -| Param | Type | Description | -| --- | --- | --- | -| key | string | Required. The key of the element to delete from The Enmap. | -| path | string | Optional. The name of the property to remove from the object. Should be a path with dot notation, such as "prop1.subprop2.subprop3" | +| Param | Type | Description | +| ----- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| key | string | Required. The key of the element to delete from The Enmap. | +| path | string | Optional. The name of the property to remove from the object. Should be a path with dot notation, such as "prop1.subprop2.subprop3" | ### enmap.clear() ⇒ void + Deletes everything from the enmap. **Kind**: instance method of Enmap ### enmap.remove(key, val, path) -Remove a value in an Array or Object element in Enmap. Note that this only works for values, not keys. Note that only one value is removed, no more. Arrays of objects must use a function to remove, as full object matching is not supported. -**Kind**: instance method of Enmap +Remove a value in an Array or Object element in Enmap. Note that this only works for +values, not keys. Note that only one value is removed, no more. Arrays of objects must use a function to remove, +as full object matching is not supported. -| Param | Type | Description | -| --- | --- | --- | -| key | string | Required. The key of the element to remove from in Enmap. | -| 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. | -| 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. | +**Kind**: instance method of Enmap + +| Param | Type | Description | +| ----- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| key | string | Required. The key of the element to remove from in Enmap. | +| 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. | +| 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. | + +**Example** -**Example** ```js -// Assuming enmap.set('array', [1, 2, 3]) enmap.set('objectarray', [{ a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 }]) enmap.remove('array', 1); // value is now [2, 3] enmap.remove('objectarray', (value) => value.e === 5); // value is now [{ a: 1, b: 2, c: 3 }] +// Assuming +enmap.set('array', [1, 2, 3]); +enmap.set('objectarray', [ + { a: 1, b: 2, c: 3 }, + { d: 4, e: 5, f: 6 }, +]); + +enmap.remove('array', 1); // value is now [2, 3] +enmap.remove('objectarray', (value) => value.e === 5); // value is now [{ a: 1, b: 2, c: 3 }] ``` + ### enmap.export() ⇒ string -Exports the enmap data to stringified JSON format. **__WARNING__**: Does not work on memory enmaps containing complex data! + +Exports the enmap data to stringified JSON format. \***\*WARNING\*\***: Does not work on memory enmaps containing complex data! **Kind**: instance method of Enmap **Returns**: string - The enmap data in a stringified JSON format. ### enmap.import(data, overwrite, clear) -Import an existing json export from enmap. This data must have been exported from enmap, and must be from a version that's equivalent or lower than where you're importing it. (This means Enmap 5 data is compatible in Enmap 6). -**Kind**: instance method of Enmap +Import an existing json export from enmap. This data must have been exported from enmap, +and must be from a version that's equivalent or lower than where you're importing it. +(This means Enmap 5 data is compatible in Enmap 6). -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| data | string | | The data to import to Enmap. Must contain all the required fields provided by an enmap export(). | -| overwrite | boolean | true | Defaults to `true`. Whether to overwrite existing key/value data with incoming imported data | -| 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.) | +**Kind**: instance method of Enmap + +| Param | Type | Default | Description | +| --------- | -------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| data | string | | The data to import to Enmap. Must contain all the required fields provided by an enmap export(). | +| overwrite | boolean | true | Defaults to `true`. Whether to overwrite existing key/value data with incoming imported data | +| 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.) | ### enmap.random([count]) ⇒ \* \| Array.<\*> + Obtains random value(s) from this Enmap. This relies on [Enmap#array](Enmap#array). **Kind**: instance method of Enmap -**Returns**: \* \| Array.<\*> - The single value if `count` is undefined, or an array of values of `count` length +**Returns**: \* \| Array.<\*> - The single value if `count` is undefined, +or an array of values of `count` length -| Param | Type | Default | Description | -| --- | --- | --- | --- | +| Param | Type | Default | Description | +| ------- | ------------------- | -------------- | ----------------------------------- | | [count] | number | 1 | Number of values to obtain randomly | ### enmap.randomKey([count]) ⇒ \* \| Array.<\*> + Obtains random key(s) from this Enmap. This relies on [Enmap#keyArray](Enmap#keyArray) **Kind**: instance method of Enmap -**Returns**: \* \| Array.<\*> - The single key if `count` is undefined, or an array of keys of `count` length +**Returns**: \* \| Array.<\*> - The single key if `count` is undefined, +or an array of keys of `count` length -| Param | Type | Default | Description | -| --- | --- | --- | --- | +| Param | Type | Default | Description | +| ------- | ------------------- | -------------- | --------------------------------- | | [count] | number | 1 | Number of keys to obtain randomly | ### enmap.every(valueOrFunction, [path]) ⇒ boolean -Similar to [Array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every). Supports either a predicate function or a value to compare. Returns true only if the predicate function returns true for all elements in the array (or the value is strictly equal in all elements). -**Kind**: instance method of Enmap +Similar to +[Array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every). +Supports either a predicate function or a value to compare. +Returns true only if the predicate function returns true for all elements in the array (or the value is strictly equal in all elements). + +**Kind**: instance method of Enmap -| Param | Type | Description | -| --- | --- | --- | -| valueOrFunction | function \| string | Function used to test (should return a boolean), or a value to compare. | -| [path] | string | Required if the value is an object. The path to the property to compare with. | +| Param | Type | Description | +| --------------- | -------------------------------------------- | ----------------------------------------------------------------------------- | +| valueOrFunction | function \| string | Function used to test (should return a boolean), or a value to compare. | +| [path] | string | Required if the value is an object. The path to the property to compare with. | ### enmap.some(valueOrFunction, [path]) ⇒ Array -Similar to [Array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some). Supports either a predicate function or a value to compare. 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). -**Kind**: instance method of Enmap +Similar to +[Array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some). +Supports either a predicate function or a value to compare. +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). -| Param | Type | Description | -| --- | --- | --- | -| valueOrFunction | function \| string | Function used to test (should return a boolean), or a value to compare. | -| [path] | string | Required if the value is an object. The path to the property to compare with. | +**Kind**: instance method of Enmap + +| Param | Type | Description | +| --------------- | -------------------------------------------- | ----------------------------------------------------------------------------- | +| valueOrFunction | function \| string | Function used to test (should return a boolean), or a value to compare. | +| [path] | string | Required if the value is an object. The path to the property to compare with. | ### enmap.map(pathOrFn) ⇒ Array -Similar to [Array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Returns an array of the results of applying the callback to all elements. -**Kind**: instance method of Enmap +Similar to +[Array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). +Returns an array of the results of applying the callback to all elements. + +**Kind**: instance method of Enmap -| Param | Type | Description | -| --- | --- | --- | +| Param | Type | Description | +| -------- | -------------------------------------------- | --------------------------------------------------------------------------------------- | | pathOrFn | function \| string | A function that produces an element of the new Array, or a path to the property to map. | ### enmap.find(pathOrFn, [value]) ⇒ \* -Searches for a single item where its specified property's value is identical to the given value (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is similar to [Array.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find). -**Kind**: instance method of Enmap +Searches for a single item where its specified property's value is identical to the given value +(`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is similar to +[Array.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find). + +**Kind**: instance method of Enmap -| Param | Type | Description | -| --- | --- | --- | -| pathOrFn | string \| function | The path to the value to test against, or the function to test with | -| [value] | \* | The expected value - only applicable and required if using a property for the first argument | +| Param | Type | Description | +| -------- | -------------------------------------------- | -------------------------------------------------------------------------------------------- | +| pathOrFn | string \| function | The path to the value to test against, or the function to test with | +| [value] | \* | The expected value - only applicable and required if using a property for the first argument | + +**Example** -**Example** ```js enmap.find('username', 'Bob'); ``` -**Example** + +**Example** + ```js -enmap.find(val => val.username === 'Bob'); +enmap.find((val) => val.username === 'Bob'); ``` + ### enmap.findIndex(pathOrFn, [value]) ⇒ string \| number -Searches for the key of a single item where its specified property's value is identical to the given value (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is similar to [Array.findIndex()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex). -**Kind**: instance method of Enmap +Searches for the key of a single item where its specified property's value is identical to the given value +(`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is similar to +[Array.findIndex()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex). + +**Kind**: instance method of Enmap -| Param | Type | Description | -| --- | --- | --- | -| pathOrFn | string \| function | The path to the value to test against, or the function to test with | -| [value] | \* | The expected value - only applicable and required if using a property for the first argument | +| Param | Type | Description | +| -------- | -------------------------------------------- | -------------------------------------------------------------------------------------------- | +| pathOrFn | string \| function | The path to the value to test against, or the function to test with | +| [value] | \* | The expected value - only applicable and required if using a property for the first argument | + +**Example** -**Example** ```js enmap.findIndex('username', 'Bob'); ``` -**Example** + +**Example** + ```js -enmap.findIndex(val => val.username === 'Bob'); +enmap.findIndex((val) => val.username === 'Bob'); ``` + ### enmap.reduce(predicate, [initialValue]) ⇒ \* -Similar to [Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). -**Kind**: instance method of Enmap +Similar to +[Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). -| Param | Type | Description | -| --- | --- | --- | -| predicate | function | Function used to reduce, taking three arguments; `accumulator`, `currentValue`, `currentKey`. | -| [initialValue] | \* | Starting value for the accumulator | +**Kind**: instance method of Enmap + +| Param | Type | Description | +| -------------- | --------------------- | --------------------------------------------------------------------------------------------- | +| predicate | function | Function used to reduce, taking three arguments; `accumulator`, `currentValue`, `currentKey`. | +| [initialValue] | \* | Starting value for the accumulator | ### enmap.filter(pathOrFn, [value]) ⇒ Enmap -Similar to [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). Returns an array of values where the given function returns true for that value. Alternatively you can provide a value and path to filter by using exact value matching. -**Kind**: instance method of Enmap +Similar to +[Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). +Returns an array of values where the given function returns true for that value. +Alternatively you can provide a value and path to filter by using exact value matching. + +**Kind**: instance method of Enmap -| Param | Type | Description | -| --- | --- | --- | +| Param | Type | Description | +| -------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | 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. | -| [value] | string | Value to use as `this` when executing function | +| [value] | string | Value to use as `this` when executing function | ### enmap.sweep(pathOrFn, [value]) ⇒ number + Deletes entries that satisfy the provided filter function or value matching. **Kind**: instance method of Enmap -**Returns**: number - The number of removed entries. +**Returns**: number - The number of removed entries. -| Param | Type | Description | -| --- | --- | --- | -| pathOrFn | function \| string | The path to the value to test against, or the function to test with. | -| [value] | \* | The expected value - only applicable and required if using a property for the first argument. | +| Param | Type | Description | +| -------- | -------------------------------------------- | --------------------------------------------------------------------------------------------- | +| pathOrFn | function \| string | The path to the value to test against, or the function to test with. | +| [value] | \* | The expected value - only applicable and required if using a property for the first argument. | ### enmap.changed(cb) -Function called whenever data changes within Enmap after the initial load. Can be used to detect if another part of your code changed a value in enmap and react on it. -**Kind**: instance method of Enmap +Function called whenever data changes within Enmap after the initial load. +Can be used to detect if another part of your code changed a value in enmap and react on it. + +**Kind**: instance method of Enmap -| Param | Type | Description | -| --- | --- | --- | -| cb | function | A callback function that will be called whenever data changes in the enmap. | +| Param | Type | Description | +| ----- | --------------------- | --------------------------------------------------------------------------- | +| cb | function | A callback function that will be called whenever data changes in the enmap. | + +**Example** -**Example** ```js -enmap.changed((keyName, oldValue, newValue) => { console.log(`Value of ${keyName} has changed from: \n${oldValue}\nto\n${newValue}`); }); +enmap.changed((keyName, oldValue, newValue) => { + console.log( + `Value of ${keyName} has changed from: \n${oldValue}\nto\n${newValue}`, + ); +}); ``` + ### enmap.partition(pathOrFn, value) ⇒ Array.<Array.<\*>> + Separates the Enmap into multiple arrays given a function that separates them. **Kind**: instance method of Enmap -**Returns**: Array.<Array.<\*>> - An array of arrays with the partitioned data. +**Returns**: Array.<Array.<\*>> - An array of arrays with the partitioned data. -| Param | Type | Description | -| --- | --- | --- | +| Param | Type | Description | +| -------- | --------------- | -------------------------------------------------------------------- | | pathOrFn | \* | the path to the value to test against, or the function to test with. | -| value | \* | the value to use as a condition for partitioning. | +| value | \* | the value to use as a condition for partitioning. | ### Enmap.multi(names, options) ⇒ Object + Initialize multiple Enmaps easily. **Kind**: static method of Enmap -**Returns**: Object - An array of initialized Enmaps. +**Returns**: Object - An array of initialized Enmaps. + +| Param | Type | Description | +| ------- | --------------------------------- | ------------------------------------------------------------------------------- | +| names | Array.<string> | Array of strings. Each array entry will create a separate enmap with that name. | +| options | Object | Options object to pass to each enmap, excluding the name.. | -| Param | Type | Description | -| --- | --- | --- | -| names | Array.<string> | Array of strings. Each array entry will create a separate enmap with that name. | -| options | Object | Options object to pass to each enmap, excluding the name.. | +**Example** -**Example** ```js -// Using local variables. const Enmap = require('enmap'); const { settings, tags, blacklist } = Enmap.multi(['settings', 'tags', 'blacklist']); // Attaching to an existing object (for instance some API's client) const Enmap = require("enmap"); Object.assign(client, Enmap.multi(["settings", "tags", "blacklist"])); +// Using local variables. +const Enmap = require('enmap'); +const { settings, tags, blacklist } = Enmap.multi([ + 'settings', + 'tags', + 'blacklist', +]); + +// Attaching to an existing object (for instance some API's client) +const Enmap = require('enmap'); +Object.assign(client, Enmap.multi(['settings', 'tags', 'blacklist'])); ``` diff --git a/src/index.js b/src/index.js index 18fa851..daaf325 100644 --- a/src/index.js +++ b/src/index.js @@ -42,7 +42,7 @@ class Enmap { /** * Initializes a new Enmap, with options. - * @param {Object} [options] Options for the enmap. See https://enmap.evie.codes/usage#enmap-options for details. + * @param {Object} [options] Options for the enmap. See https://enmap.evie.dev/usage#enmap-options for details. * @param {string} [options.name] The name of the enmap. Represents its table name in sqlite. Unless inMemory is set to true, the enmap will be persisted to disk. diff --git a/typings/index.d.ts b/typings/index.d.ts index 377f9c1..b5e4aea 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -144,7 +144,7 @@ declare module 'enmap' { * @param iterable If iterable data, only valid in non-persistent enmaps. * If this parameter is a string, it is assumed to be the enmap's name, which is a shorthand for adding a name in the options * and making the enmap persistent. - * @param options Additional options for the enmap. See https://enmap.evie.codes/usage#enmap-options for details. + * @param options Additional options for the enmap. See https://enmap.evie.dev/usage#enmap-options for details. * @example * const Enmap = require("enmap"); * // Non-persistent enmap: