maraj 1.0.8 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,107 +1,93 @@
1
1
 
2
2
  # Maraj
3
3
 
4
- A lightweight alternative for creating **immutable updates of objects and arrays.**
4
+ A lightweight alternative for creating **immutable updates of objects and arrays** such as Immer or ImmutableJS.
5
5
 
6
- **4 times faster** than the commonly used alternatives like Immer or ImmutableJS.
6
+ **4 times faster** and **over 10 times lighter**.
7
7
 
8
- Only **600 bytes** gziped with 5 common utilities that you will most likelly need in every project.
8
+ Only **400 bytes** gziped and additional **300 bytes** for 4 common utilities that you will most likelly need in every project.
9
9
 
10
10
  Features:
11
11
  - Can accept multiple updates while mantaining the order of execution.
12
12
  - Easy syntax for conditional updates.
13
13
  - Functional updates.
14
14
 
15
+ Vitest: https://www.npmjs.com/package/maraj-test
16
+
15
17
  ## Creating an Immutable Update
16
18
 
17
19
  The **createImmutableUpdate** function has two arguments:
18
- 1. The **original object** we want to update non-destructively
19
- 2. An **update object** with key-value pairs representing the updates we want to make
20
-
21
- The **updateObject** has the following syntax:
20
+ 1. The **Original object**.
21
+ 2. An **Update object** (key-value pairs representing the updates we want to make)
22
22
 
23
- It can accept multiple key-value pairs and the order of execution will be preserved.
23
+ The **Update Object** has the following syntax:
24
+ ```js
25
+ {
26
+ 'my.path.separated.by.dots': 'The new value',
27
+ 'another.path': 'new value',
28
+ 'myArray.0.name': 'new name in object inside array at index 0',
29
+ [false && 'path.conditionalUpdate']: true
30
+ }
31
+ ```
32
+ Multiple key-value pairs that mantains the order of execution.
24
33
 
25
- - **Key:** path name of the fiels, separated by commas (same syntax you use to access object/array properties)
34
+ - **Keys:** path name of the fiels, separated by dots.
26
35
  - For arrays just use its index value
27
- - Can accept conditional statements. (If the key is falsy, undefined or null it will not update the new value into the new object.)
36
+ - Can accept conditional statements. (If the key = false or undefined or null it will skip that field update.)
28
37
 
29
- - **Value:** can be any type, including a function, where its argument will be the current value and its return value has to be the new value to be updated
38
+ - **Value:** new value, any type. If its a function it ll be called with the current value in that field.
30
39
 
31
40
 
32
41
  ## Example
33
42
 
34
43
  ```js
35
- import createImmutableUpdate from 'maraj'
36
-
37
- const person = {
38
- name: 'Lukasz',
39
- country: 'Spain',
40
- additionalInfo:{
41
- info1: null,
42
- info2: null,
43
- info3: null,
44
- info4: null
45
- }
46
- projects: [
47
- {
48
- title: 'portfolio',
49
- languages: ['esp','eng'],
50
- description: 'lorem ipsum',
51
- available: false,
52
- data:{
53
- createdAt: '01-01-2000',
54
- size: 20000
55
- }
56
- },
57
- {
58
- title: 'asia',
59
- languages: ['esp','eng'],
60
- description: 'lorem ipsum',
61
- available: true,
62
- data:{
63
- createdAt: '01-01-2000',
64
- size: 40000
65
- }
66
- },
67
- {
68
- title: 'pos',
69
- languages: ['esp','eng'],
70
- description: 'lorem ipsum',
71
- available: false,
72
- data:{
73
- createdAt: '01-01-2000',
74
- size: 100000
75
- }
76
- }
44
+ import createImmutableUpdate, { spread } from "maraj";
45
+
46
+ const data = {
47
+ person: { name: "Lukasz", works: ["soum", "fi"] },
48
+ works: [
49
+ { title: "soum", size: 90, available: true, info: ["info1"] },
50
+ { title: "fi", size: 30, available: false, info: ["infoA"] },
77
51
  ]
78
52
  }
79
53
 
80
- const newUpdatedObject = createImmutableUpdate(person,{
81
- 'name': 'maraj', //normal update
82
- 'projects.0.title': 'website', //nested update
83
- 'projects.1.available': true, //nested update
84
- 'projects.1.available': (currentValue) => !currentValue, //functional update
85
- 'projects': (currentValue) => currentValue.filter(project => project.available), //functional update
86
- [condition && 'additionalInfo.info1']: 'some info' //conditional update, only if the key is not false/undefined/null
54
+ const newUpdatedObject = createImmutableUpdate(data, {
55
+ "age": 28, //add new values
56
+ "person.name": "Lucas", //update values
57
+ "person.works.1": "gs", //nested array update
58
+ "works.1.available": (currentValue) => (!currentValue), //functional update
59
+ [false && "works.0.size"]: 120, //conditional field update
60
+ "person.works": spread("portfolio") //common utilities
87
61
  })
62
+
63
+ /** Does not make a deep copy and "falsy" fields are ignored */
64
+ newUpdatedObject.works[0] === data.works[0] //true
65
+
66
+ /** New Updated Object
67
+ {
68
+ person: { name: "Lucas", works: ["soum", "gs", "portfolio"], age: 28 },
69
+ works: [
70
+ { title: "soum", size: 90, available: true, info: ["info1"] },
71
+ { title: "fi", size: 30, available: true, info: ["infoA"] },
72
+ ]
73
+ }
74
+ */
88
75
  ```
89
76
 
90
77
  ## Other Utilities
91
78
 
92
79
  ### spread
93
80
 
94
- Spreads its argument into the key provided in the **createImmutableUpdate.**
95
-
96
- Works with **objects (updates its keys)**, **arrays (adds new values to the array)** and **any other value (sets the new value)**
81
+ **For Objects and Arrays: Spreads** its argument into the key provided in the createImmutableUpdate.
82
+ **For the rest: Sets** its argument into the key provided in the createImmutableUpdate.
97
83
 
98
84
  ```js
99
85
  import {spread} from 'maraj'
100
86
 
101
- const newUpdatedObject = createImmutableUpdate(person,{
102
- 'additionalInfo': spread({info1: 'new Info'}), //same as (newValue) => (value) => ({...value, ...newValue})
103
- 'projects': spread({title: 'new project'}) //same as (newValueToAdd) => (value) => ([...value, ...newValueToAdd])
104
- 'additionalInfo.info1': spread('new project') //same as (newValue) => (value) => (newValue)
87
+ const newUpdatedObject = createImmutableUpdate(data,{
88
+ 'person': spread({info1: 'new Info'}), //same as (newValue) => (value) => ({...value, ...newValue})
89
+ 'works': spread({title: 'new project', size: 20}) //same as (newValueToAdd) => (value) => ([...value, ...newValueToAdd])
90
+ 'person.works': spread("portfolio") //same as (newValue) => (value) => (newValue)
105
91
  })
106
92
  ```
107
93
 
@@ -113,8 +99,8 @@ Removes the **key of an object** or the **index of an array** in the key provide
113
99
  import {remove} from 'maraj'
114
100
 
115
101
  const newUpdatedObject = createImmutableUpdate(person,{
116
- 'additionalInfo': remove('info1'), // returns new value (in this case "additionalInfo") without the provided key ("info1")
117
- 'projects': remove(1) // returns new array (in this case "projects") without the provided index (1)
102
+ 'person': remove('works'), // returns new value (in this case "person") without the provided key ("works")
103
+ 'works': remove(1) // returns new array (in this case "works") without the provided index (1)
118
104
  })
119
105
  ```
120
106
 
@@ -127,9 +113,9 @@ Usefull in cases like getting data from Redux, Zustand, and so on. stores.
127
113
  ```js
128
114
  import {createSelectorFromStringPath} from 'maraj'
129
115
 
130
- const stringPath = 'projects.1.data.size'
116
+ const stringPath = 'works.1.size'
131
117
 
132
- const storeSelector = createSelectorFromStringPath(stringPath) // will behave as (store) => store[projects][1][data][size]
118
+ const storeSelector = createSelectorFromStringPath(stringPath) // will behave as (store) => store[works][1][size]
133
119
  ```
134
120
 
135
121
  ### splitPath
@@ -144,9 +130,9 @@ Splits string path (example:'projects.1.data.size' ) into two:
144
130
  ```js
145
131
  import {splitPath} from 'maraj'
146
132
 
147
- const stringPath = 'projects.1.data.size'
133
+ const stringPath = 'works.1.size'
148
134
 
149
135
  const { id, remainingPath } = splitPath(stringPath)
150
136
  // id = 'size'
151
- // remainingPath = 'projects.1.data'
137
+ // remainingPath = 'works.1'
152
138
  ```
package/maraj.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @file maraj.js is the root file for this example app
3
+ * @author Lukasz Maraj
4
+ * @see <a href="https://lukaszmaraj.com">Lukasz Maraj</a>
5
+ */
6
+ /**
7
+ * Returns a new updated state (new object/array)
8
+ * @param {object} state - object or array to update immutably
9
+ * @param {object} update - update object
10
+ * @returns - new updated state
11
+ */
12
+ declare const createImmutableUpdate: (state: any, update?: {}) => any;
13
+ export default createImmutableUpdate;
14
+ /**
15
+ * Spreads if its an object or array to the target, if its not then it sets its value
16
+ * @param {*} update - any
17
+ * @returns - updated value; spreaded if object/array, overwritted for the rest of the cases
18
+ */
19
+ export declare const spread: (update: any) => (value: any) => any;
20
+ /**
21
+ * Removes properties or indexes; skips the ones dont exist
22
+ * @param {string | number | string[] | number[]} keys - properties or indexes to be removed
23
+ * @returns - new updated value
24
+ */
25
+ export declare const remove: (keys: string | number | string[] | number[]) => (value: any) => any;
26
+ /**
27
+ * Creates a selector with a string path
28
+ * @param {string} path - path, ex: 'login.form.username.value'
29
+ * @returns - store selector
30
+ */
31
+ export declare const createSelectorFromStringPath: (path: string) => (state: any) => any;
32
+ /**
33
+ * Splits string path into ID and RemainingPath
34
+ * @param {string} path - Path separated by dots
35
+ * @returns {id: string, remainingPath: string} - {id: string, remainingPath: string | ''}
36
+ */
37
+ export declare const splitPath: (path: string) => {
38
+ id: string;
39
+ remainingPath: string;
40
+ };
package/maraj.js ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @file maraj.js is the root file for this example app
3
+ * @author Lukasz Maraj
4
+ * @see <a href="https://lukaszmaraj.com">Lukasz Maraj</a>
5
+ */
6
+
7
+
8
+ /**
9
+ * Returns a new updated state (new object/array)
10
+ * @param {object} state - object or array to update immutably
11
+ * @param {object} update - update object
12
+ * @returns - new updated state
13
+ */
14
+ const createImmutableUpdate = (state, update = {}) => {
15
+ if (state?.constructor !== Object && !Array.isArray(state)) return state
16
+ const newState = Array.isArray(state) ? [...state] : { ...state }
17
+ const visited = {}
18
+ for (const [path, value] of Object.entries(update)) {
19
+ if (!path || path === 'false' || path === 'undefined' || path === 'null') continue
20
+ let keys = path.split(".")
21
+ let lastkey = keys.pop()
22
+ let tracker = visited
23
+ let current = newState
24
+ for (let key of keys) {
25
+ if (typeof current[key] !== 'object') throw new Error(`Destructure "${key}" in "${path}" with value: ${current[key]}`)
26
+ if (!tracker[key]) {
27
+ current[key] = Array.isArray(current[key]) ? [...current[key]] : { ...current[key] }
28
+ tracker[key] = {}
29
+ }
30
+ current = current[key]
31
+ tracker = tracker[key]
32
+ }
33
+ delete tracker[lastkey]
34
+ current[lastkey] = typeof value === 'function' ? value(current[lastkey]) : value
35
+ }
36
+ return newState
37
+ }
38
+ export default createImmutableUpdate
39
+
40
+
41
+ /**
42
+ * Spreads if its an object or array to the target, if its not then it sets its value
43
+ * @param {*} update - any
44
+ * @returns - updated value; spreaded if object/array, overwritted for the rest of the cases
45
+ */
46
+ export const spread = (update) => (value) => {
47
+ if (value?.constructor === Object && update?.constructor === Object) return { ...value, ...update }
48
+ if (Array.isArray(value) && Array.isArray(update)) return [...value, ...update]
49
+ return update
50
+ }
51
+
52
+
53
+ /**
54
+ * Removes properties or indexes; skips the ones dont exist
55
+ * @param {string | number | string[] | number[]} keys - properties or indexes to be removed
56
+ * @returns - new updated value
57
+ */
58
+ export const remove = (keys) => (value) => {
59
+ if (typeof value !== 'object') return value
60
+ if (typeof keys !== 'object' || keys === null) keys = [keys]
61
+ if (Array.isArray(value)) {
62
+ const values = keys.map(key => value[key])
63
+ return value.filter(v => (!values.includes(v) || (values.splice(values.indexOf(v), 1) && false)))
64
+ }
65
+ const update = { ...value }
66
+ keys.forEach(key => delete update[key])
67
+ return update
68
+ }
69
+
70
+
71
+ /**
72
+ * Creates a selector with a string path
73
+ * @param {string} path - path, ex: 'login.form.username.value'
74
+ * @returns - store selector || undefined
75
+ */
76
+ export const createSelectorFromStringPath = (path) => (state) => {
77
+ if (typeof path !== 'string') throw new Error('Path should be string')
78
+ if (!path) return state
79
+ return path.split(".").reduce((current, key) => {
80
+ if (current?.hasOwnProperty(key)) return current[key]
81
+ console.log('current', current)
82
+ return undefined
83
+ }, state)
84
+ }
85
+
86
+
87
+ /**
88
+ * Splits string path into ID and RemainingPath
89
+ * @param {string} path - Path separated by dots
90
+ * @returns {id: string, remainingPath: string} - {id: string, remainingPath: string | ''}
91
+ */
92
+ // splits a string id path
93
+ export const splitPath = (path) => {
94
+ if (typeof path !== 'string') throw new Error(`Provided path is not a string ${path}`)
95
+ const lastDot = path.lastIndexOf(".") + 1
96
+ return {
97
+ id: path.slice(lastDot),
98
+ remainingPath: lastDot ? path.slice(0, lastDot - 1) : ''
99
+ }
100
+ }
package/package.json CHANGED
@@ -1,11 +1,16 @@
1
1
  {
2
2
  "name": "maraj",
3
- "version": "1.0.8",
4
- "description": "A lightweight 600 bytes gzipped alternative for immutable updates while dealing with objects and arrays",
5
- "main": "index.js",
3
+ "version": "1.1.1",
4
+ "description": "A lightweight 500 bytes gzipped alternative for immutable updates while dealing with objects and arrays",
5
+ "main": "maraj.js",
6
+ "type": "module",
6
7
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
+ "test": "vitest"
8
9
  },
9
10
  "author": "Lukasz Maraj",
10
- "license": "ISC"
11
- }
11
+ "license": "MIT",
12
+ "devDependencies": {
13
+ "typescript": "^4.9.5",
14
+ "vitest": "^0.28.4"
15
+ }
16
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,104 @@
1
+ {
2
+ "include": ["./"],
3
+ "compilerOptions": {
4
+ /* Visit https://aka.ms/tsconfig to read more about this file */
5
+
6
+ /* Projects */
7
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
8
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
9
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
10
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
11
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
12
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
13
+
14
+ /* Language and Environment */
15
+ "target": "ES2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
16
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
17
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
18
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
19
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27
+
28
+ /* Modules */
29
+ "module": "commonjs", /* Specify what module code is generated. */
30
+ // "rootDir": "./", /* Specify the root folder within your source files. */
31
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
32
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
33
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
34
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
36
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
37
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
38
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
39
+ // "resolveJsonModule": true, /* Enable importing .json files. */
40
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
41
+
42
+ /* JavaScript Support */
43
+ "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
44
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
45
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
46
+
47
+ /* Emit */
48
+ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
49
+ "declarationMap": true, /* Create sourcemaps for d.ts files. */
50
+ "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
51
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
52
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
53
+ "outDir": "dist", /* Specify an output folder for all emitted files. */
54
+ // "removeComments": true, /* Disable emitting comments. */
55
+ // "noEmit": true, /* Disable emitting files from a compilation. */
56
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
57
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
58
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
59
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
60
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
61
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
62
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
63
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
64
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
65
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
66
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
67
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
68
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
69
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
70
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
71
+
72
+ /* Interop Constraints */
73
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
74
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
75
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
76
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
77
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
78
+
79
+ /* Type Checking */
80
+ "strict": true, /* Enable all strict type-checking options. */
81
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
82
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
83
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
84
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
85
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
86
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
87
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
88
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
89
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
90
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
91
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
92
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
93
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
94
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
95
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
96
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
97
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
98
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
99
+
100
+ /* Completeness */
101
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
102
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
103
+ }
104
+ }
package/index.js DELETED
@@ -1,49 +0,0 @@
1
- //creates a shallow deep copy with the only needed updated fields
2
- const createImmutableUpdate = (state, update = {}) => {
3
- const newState = Array.isArray(state) ? [...state] : { ...state }
4
- const visited = {}
5
- for (const [path, value] of Object.entries(update)) {
6
- if (!path || path === 'false' || path === 'undefined' || path === 'null') continue
7
- let keys = path.split(".")
8
- let lastkey = keys.pop()
9
- let tracker = visited
10
- let current = newState
11
- for (let key of keys) {
12
- if (typeof current[key] !== 'object') throw new Error(`Destructure "${key}" in "${path}" with value: ${current[key]}`)
13
- if (!tracker[key]) {
14
- current[key] = Array.isArray(current[key]) ? [...current[key]] : { ...current[key] }
15
- tracker[key] = {}
16
- }
17
- current = current[key]
18
- tracker = tracker[key]
19
- }
20
- delete tracker[lastkey]
21
- current[lastkey] = typeof value === 'function' ? value(current[lastkey]) : value
22
- }
23
- return newState
24
- }
25
- export default createImmutableUpdate
26
-
27
- export const createSelectorFromStringPath = (path) => (state) => path.split(".").reduce((current, key) => current[key], state)
28
-
29
- // spread object or array, if its not object or array it just assigns its value
30
- export const spread = (update) => (value) => {
31
- if (value?.constructor === Object && update?.constructor === Object) return { ...value, ...update }
32
- if (Array.isArray(value) && Array.isArray(update)) return [...value, ...update]
33
- return update
34
- }
35
-
36
- // a string/number/array of index or properties(key)
37
- export const remove = (keys) => (value) => {
38
- if (typeof value !== 'object') return value
39
- if (typeof keys !== 'object') keys = [keys]
40
- if (Array.isArray(value)) return value.filter((v, i) => (!keys.includes(i) || (keys.splice(keys.indexOf(i), 1) && false)))
41
- const update = { ...value }
42
- keys.forEach(key => delete update[key])
43
- return update
44
- }
45
- // splits a string id path
46
- export const splitPath = (path) => ({
47
- remainingPath: path.slice(0, path.lastIndexOf(".") + 1),
48
- id: path.slice(path.lastIndexOf(".") + 1),
49
- })