maraj 1.1.2 → 2.0.0

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/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2023 Lukasz Maraj
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,138 +1,143 @@
1
-
2
- # Maraj
3
-
4
- A lightweight alternative for creating **immutable updates of objects and arrays** such as Immer or ImmutableJS.
5
-
6
- **4 times faster** and **over 10 times lighter**.
7
-
8
- Only **400 bytes** gziped and additional **300 bytes** for 4 common utilities that you will most likelly need in every project.
9
-
10
- Features:
11
- - Can accept multiple updates while mantaining the order of execution.
12
- - Easy syntax for conditional updates.
13
- - Functional updates.
14
-
15
- Vitest: https://www.npmjs.com/package/maraj-test
16
-
17
- ## Creating an Immutable Update
18
-
19
- The **createImmutableUpdate** function has two arguments:
20
- 1. The **Original object**.
21
- 2. An **Update object** (key-value pairs representing the updates we want to make)
22
-
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.
33
-
34
- - **Keys:** path name of the fiels, separated by dots.
35
- - For arrays just use its index value
36
- - Can accept conditional statements. (If the key = false or undefined or null it will skip that field update.)
37
-
38
- - **Value:** new value, any type. If its a function it ll be called with the current value in that field.
39
-
40
-
41
- ## Example
42
-
43
- ```js
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"] },
51
- ]
52
- }
53
-
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
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
- */
75
- ```
76
-
77
- ## Other Utilities
78
-
79
- ### spread
80
-
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.
83
-
84
- ```js
85
- import {spread} from 'maraj'
86
-
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)
91
- })
92
- ```
93
-
94
- ### remove
95
-
96
- Removes the **key of an object** or the **index of an array** in the key provided in the **createImmutableUpdate.**
97
-
98
- ```js
99
- import {remove} from 'maraj'
100
-
101
- const newUpdatedObject = createImmutableUpdate(person,{
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)
104
- })
105
- ```
106
-
107
- ### createSelectorFromStringPath
108
-
109
- **Creates a store selector** from provided string path.
110
-
111
- Usefull in cases like getting data from Redux, Zustand, and so on. stores.
112
-
113
- ```js
114
- import {createSelectorFromStringPath} from 'maraj'
115
-
116
- const stringPath = 'works.1.size'
117
-
118
- const storeSelector = createSelectorFromStringPath(stringPath) // will behave as (store) => store[works][1][size]
119
- ```
120
-
121
- ### splitPath
122
-
123
- Usefull when you want to spread multiple values into objects dynamically
124
-
125
- Splits string path (example:'projects.1.data.size' ) into two:
126
- - id: the last key in the path (in this case 'size')
127
- - remainingPath: the remaining path (in this case 'projects.1.data')
128
-
129
-
130
- ```js
131
- import {splitPath} from 'maraj'
132
-
133
- const stringPath = 'works.1.size'
134
-
135
- const { id, remainingPath } = splitPath(stringPath)
136
- // id = 'size'
137
- // remainingPath = 'works.1'
138
- ```
1
+
2
+ # Maraj
3
+
4
+ A lightweight alternative for creating **immutable updates of objects and arrays** such as Immer or ImmutableJS.
5
+
6
+ **4 times faster** and **over 10 times lighter**.
7
+
8
+ Fully typed.
9
+
10
+ Only **400 bytes** gziped and additional **300 bytes** for 4 common utilities that you will most likelly need in every project.
11
+
12
+ Features:
13
+
14
+ - Can accept multiple updates while mantaining the order of execution.
15
+ - Easy syntax for conditional updates.
16
+ - Functional updates.
17
+
18
+ Set "strictNullChecks" and "noUncheckedIndexedAccess" to true in tsconfig.json for correct type inference in optional properties (so it can correctly differentiate between optional props and props with possible undefined value)
19
+
20
+ ## Creating an Immutable Update
21
+
22
+ The **updateImmutably** function has two arguments:
23
+
24
+ 1. The **Original object**.
25
+ 2. An **Update object** (key-value pairs representing the updates we want to make)
26
+
27
+ The **Update Object** has the following syntax:
28
+
29
+ ```js
30
+ {
31
+ 'my.path.separated.by.dots': 'The new value',
32
+ 'another.path': 'new value',
33
+ 'myArray.0.name': 'new name in object inside array at index 0',
34
+ [false && 'path.conditionalUpdate']: true
35
+ }
36
+ ```
37
+
38
+ Multiple key-value pairs that mantains the order of execution.
39
+
40
+ - **Keys:** path name of the fiels, separated by dots.
41
+ - For arrays just use its index value
42
+ - Can accept conditional statements. (If the key = false or undefined or null it will skip that field update.)
43
+
44
+ - **Value:** new value, any type. If its a function it ll be called with the current value in that field.
45
+
46
+ ## Example
47
+
48
+ ```js
49
+ import updateImmutably, { spread } from "maraj";
50
+
51
+ const data = {
52
+ person: { name: "Lukasz", works: ["soum", "fi"] },
53
+ works: [
54
+ { title: "soum", size: 90, available: true, info: ["info1"] },
55
+ { title: "fi", size: 30, available: false, info: ["infoA"] },
56
+ ]
57
+ }
58
+
59
+ const newUpdatedObject = updateImmutably(data, {
60
+ "age": 28, //add new values
61
+ "person.name": "Lucas", //update values
62
+ "person.works.1": "gs", //nested array update
63
+ "works.1.available": (currentValue) => (!currentValue), //functional update
64
+ [false && "works.0.size"]: 120, //conditional field update
65
+ "person.works": (v) => spread(v, "portfolio") //common utilities
66
+ })
67
+
68
+ /** Does not make a deep copy and "falsy" fields are ignored */
69
+ newUpdatedObject.works[0] === data.works[0] //true
70
+
71
+ /** New Updated Object
72
+ {
73
+ person: { name: "Lucas", works: ["soum", "gs", "portfolio"], age: 28 },
74
+ works: [
75
+ { title: "soum", size: 90, available: true, info: ["info1"] },
76
+ { title: "fi", size: 30, available: true, info: ["infoA"] },
77
+ ]
78
+ }
79
+ */
80
+ ```
81
+
82
+ ## Other Utilities
83
+
84
+ ### spread
85
+
86
+ **For Objects and Arrays: Spreads** its argument into the key provided in the updateImmutably.
87
+ **For the rest: Sets** its argument into the key provided in the updateImmutably.
88
+
89
+ ```js
90
+ import {spread} from 'maraj'
91
+
92
+ const newUpdatedObject = updateImmutably(data,{
93
+ 'person': (value) => spread(value, {info1: 'new Info'}), //same as (newValue) => (value) => ({...value, ...newValue})
94
+ 'works': (value) => spread(value, {title: 'new project', size: 20}) //same as (newValueToAdd) => (value) => ([...value, ...newValueToAdd])
95
+ 'person.works': (value) => spread(value, "portfolio") //same as (newValue) => (value) => (newValue)
96
+ })
97
+ ```
98
+
99
+ ### remove
100
+
101
+ Removes the **key of an object** or the **index of an array** in the key provided in the **updateImmutably.**
102
+
103
+ ```js
104
+ import {remove} from 'maraj'
105
+
106
+ const newUpdatedObject = updateImmutably(person,{
107
+ 'person': (value) => remove(value, 'works'), // returns new value (in this case "person") without the provided key ("works")
108
+ 'works': (value) => remove(value, 1) // returns new array (in this case "works") without the provided index (1)
109
+ })
110
+ ```
111
+
112
+ ### select
113
+
114
+ **Creates a store selector** from provided string path.
115
+
116
+ Usefull in cases like getting data from Redux, Zustand, and so on. stores.
117
+
118
+ ```js
119
+ import {select} from 'maraj'
120
+
121
+ const stringPath = 'works.1.size'
122
+
123
+ const storeSelector = (state) => select(state, stringPath) // will behave as (store) => store[works][1][size]
124
+ ```
125
+
126
+ ### splitPathAtLastKey
127
+
128
+ Usefull when you want to spread multiple values into objects dynamically
129
+
130
+ Splits string path (example:'projects.1.data.size' ) into two:
131
+
132
+ - id: the last key in the path (in this case 'size')
133
+ - remainingPath: the remaining path (in this case 'projects.1.data')
134
+
135
+ ```js
136
+ import {splitPathAtLastKey} from 'maraj'
137
+
138
+ const stringPath = 'works.1.size'
139
+
140
+ const [remainingPath, last] = splitPathAtLastKey(stringPath)
141
+ // last = 'size'
142
+ // remainingPath = 'works.1'
143
+ ```
@@ -0,0 +1,89 @@
1
+ type Remove = <T extends object>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : (keyof T | (keyof T)[])) => T;
2
+ /**
3
+ * Removes properties or indexes, order doesn't matter.
4
+ */
5
+ declare const remove: Remove;
6
+
7
+ /**
8
+ * Paths implementation
9
+ */
10
+ type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
11
+ type IsTuple<T extends ReadonlyArray<any>> = number extends T['length'] ? false : true;
12
+ type Index = '_INDEX_';
13
+ type RootArrayPathEnum = `${number}` | Index;
14
+ type ArrayPathEnum<TLength extends boolean> = TLength extends true ? RootArrayPathEnum | 'length' : RootArrayPathEnum;
15
+ type ArrayPaths<TInnerType, TLength extends boolean> = `${ArrayPathEnum<TLength>}` | `${ArrayPathEnum<false>}.${RootFlatten<TInnerType, TLength>}`;
16
+ type FilteredTuple<T, TLength> = TLength extends string ? Omit<T, Exclude<keyof any[], 'length'>> : Omit<T, keyof any[]>;
17
+ type ObjectPaths<T, TLength extends boolean> = {
18
+ [Key in keyof T & string]: `${Key}` | `${Key}.${RootFlatten<T[Key], TLength>}`;
19
+ }[keyof T & string];
20
+ type RootFlatten<T, TIncludeLength extends boolean> = T extends ReadonlyArray<infer U> ? IsTuple<T> extends true ? ObjectPaths<FilteredTuple<T, TIncludeLength>, TIncludeLength> : ArrayPaths<U, TIncludeLength> : T extends string ? TIncludeLength extends true ? 'length' : never : T extends PrimitivesAndNativeObjects ? never : ObjectPaths<T, TIncludeLength>;
21
+ type DotPaths<T> = RootFlatten<T, false>;
22
+ type DotPathsIncludingLength<T> = RootFlatten<T, true>;
23
+ /**
24
+ * Type to know when a path is indexing an array
25
+ */
26
+ type PathIndexingArray<T extends string | number> = `${T}` | `${T}.${string}` | `${string}.${T}` | `${string}.${T}.${string}`;
27
+ /**
28
+ * Nested Property Type implementation
29
+ */
30
+ type NestedProperty<TObject, TPath extends string> = TPath extends '' ? TObject : TPath extends keyof TObject ? TObject[TPath] : TPath extends (`${number}` | Index) ? TObject extends Array<infer U> ? TPath extends `${number}.${infer K}` ? K extends keyof U ? NestedProperty<U, K> : never : U : never : TPath extends `${infer K}.${infer R}` ? K extends keyof TObject ? NestedProperty<Required<TObject>[K], R> : K extends `${number}` | Index ? TObject extends Array<infer U> ? NestedProperty<U, R> : never : never : never;
31
+ type ValueInDotPath<TObject, TPath extends DotPaths<TObject> | ''> = NestedProperty<TObject, TPath>;
32
+ /**
33
+ * Update Object Type Implementation
34
+ */
35
+ type DotPathUpdateObject<T> = Partial<{
36
+ [K in DotPaths<T>]: K extends PathIndexingArray<Index> ? [`TS PATH ERROR: replace _INDEX_ with {NUMBER}`, ValueInDotPath<T, K>, ((value: ValueInDotPath<T, K>) => ValueInDotPath<T, K>)] : ValueInDotPath<T, K> | ((value: ValueInDotPath<T, K>) => ValueInDotPath<T, K>);
37
+ }>;
38
+
39
+ type Select = <T extends object, TPath extends (DotPaths<T> | '')>(state: T, path: TPath) => TPath extends PathIndexingArray<Index> ? never : TPath extends PathIndexingArray<number> ? ValueInDotPath<T, TPath> | undefined : ValueInDotPath<T, TPath>;
40
+ /**
41
+ * Returns the value from a given dot path of an object/array.
42
+ * Returns undefined if the provided path doesnt exist.
43
+ */
44
+ declare const select: Select;
45
+
46
+ type SplitDotPathAtLastKey = <T extends string>(dotPath: T) => [string, string];
47
+ /**
48
+ * Splits string dotPath into ID and RemainingPath
49
+ */
50
+ declare const splitPathAtLastKey: SplitDotPathAtLastKey;
51
+
52
+ type Spread = <T extends object>(value: T, update: T extends Array<infer U> ? Array<U> : Partial<T>) => T;
53
+ /**
54
+ * Spreads if its an object or array to the target, if its not then returns same value
55
+ */
56
+ declare const spread: Spread;
57
+
58
+ type Set = <T>(newValue: T) => (value: T) => T;
59
+ /**
60
+ * Allows to set strongly typed values (removing inacurate "undefined" inference) in nested values inside arrays
61
+ */
62
+ declare const set: Set;
63
+
64
+ type SemiStrictMode = 'skip-non-existent-paths';
65
+ type NonStrictMode = 'implement-non-existent-paths';
66
+ type UpdateImmutably = {
67
+ <T extends object>(state: T, updates: DotPathUpdateObject<T>): T;
68
+ };
69
+ /**
70
+ * Creates a new updated object/array applying the changes provided in the update object.
71
+ * It doesnt modify the original input.
72
+ * If any of the paths doesnt exists it returns
73
+ */
74
+ declare const updateImmutably: UpdateImmutably;
75
+ type PosibleExpandedProps<T> = {
76
+ [K in keyof T]?: T[K] extends object ? PosibleExpandedProps<T[K]> & Record<any, any> : T[K];
77
+ };
78
+ type UpdateImmutablyNonStrictly = {
79
+ <T extends object>(state: T, updates: DotPathUpdateObject<T>, mode: SemiStrictMode): T;
80
+ <T extends object>(state: T, updates: DotPathUpdateObject<T>, mode: NonStrictMode): PosibleExpandedProps<T>;
81
+ };
82
+ /**
83
+ * Creates a new updated object/array applying the changes provided in the update object.
84
+ * It doesnt modify the original input.
85
+ * If any of the paths doesnt exists it adds it if possible.
86
+ */
87
+ declare const updateImmutablyAllowingNewProps: UpdateImmutablyNonStrictly;
88
+
89
+ export { type DotPathUpdateObject, type DotPaths, type DotPathsIncludingLength, type ValueInDotPath, remove, select, set, splitPathAtLastKey, spread, updateImmutably, updateImmutablyAllowingNewProps };
@@ -0,0 +1,89 @@
1
+ type Remove = <T extends object>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : (keyof T | (keyof T)[])) => T;
2
+ /**
3
+ * Removes properties or indexes, order doesn't matter.
4
+ */
5
+ declare const remove: Remove;
6
+
7
+ /**
8
+ * Paths implementation
9
+ */
10
+ type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
11
+ type IsTuple<T extends ReadonlyArray<any>> = number extends T['length'] ? false : true;
12
+ type Index = '_INDEX_';
13
+ type RootArrayPathEnum = `${number}` | Index;
14
+ type ArrayPathEnum<TLength extends boolean> = TLength extends true ? RootArrayPathEnum | 'length' : RootArrayPathEnum;
15
+ type ArrayPaths<TInnerType, TLength extends boolean> = `${ArrayPathEnum<TLength>}` | `${ArrayPathEnum<false>}.${RootFlatten<TInnerType, TLength>}`;
16
+ type FilteredTuple<T, TLength> = TLength extends string ? Omit<T, Exclude<keyof any[], 'length'>> : Omit<T, keyof any[]>;
17
+ type ObjectPaths<T, TLength extends boolean> = {
18
+ [Key in keyof T & string]: `${Key}` | `${Key}.${RootFlatten<T[Key], TLength>}`;
19
+ }[keyof T & string];
20
+ type RootFlatten<T, TIncludeLength extends boolean> = T extends ReadonlyArray<infer U> ? IsTuple<T> extends true ? ObjectPaths<FilteredTuple<T, TIncludeLength>, TIncludeLength> : ArrayPaths<U, TIncludeLength> : T extends string ? TIncludeLength extends true ? 'length' : never : T extends PrimitivesAndNativeObjects ? never : ObjectPaths<T, TIncludeLength>;
21
+ type DotPaths<T> = RootFlatten<T, false>;
22
+ type DotPathsIncludingLength<T> = RootFlatten<T, true>;
23
+ /**
24
+ * Type to know when a path is indexing an array
25
+ */
26
+ type PathIndexingArray<T extends string | number> = `${T}` | `${T}.${string}` | `${string}.${T}` | `${string}.${T}.${string}`;
27
+ /**
28
+ * Nested Property Type implementation
29
+ */
30
+ type NestedProperty<TObject, TPath extends string> = TPath extends '' ? TObject : TPath extends keyof TObject ? TObject[TPath] : TPath extends (`${number}` | Index) ? TObject extends Array<infer U> ? TPath extends `${number}.${infer K}` ? K extends keyof U ? NestedProperty<U, K> : never : U : never : TPath extends `${infer K}.${infer R}` ? K extends keyof TObject ? NestedProperty<Required<TObject>[K], R> : K extends `${number}` | Index ? TObject extends Array<infer U> ? NestedProperty<U, R> : never : never : never;
31
+ type ValueInDotPath<TObject, TPath extends DotPaths<TObject> | ''> = NestedProperty<TObject, TPath>;
32
+ /**
33
+ * Update Object Type Implementation
34
+ */
35
+ type DotPathUpdateObject<T> = Partial<{
36
+ [K in DotPaths<T>]: K extends PathIndexingArray<Index> ? [`TS PATH ERROR: replace _INDEX_ with {NUMBER}`, ValueInDotPath<T, K>, ((value: ValueInDotPath<T, K>) => ValueInDotPath<T, K>)] : ValueInDotPath<T, K> | ((value: ValueInDotPath<T, K>) => ValueInDotPath<T, K>);
37
+ }>;
38
+
39
+ type Select = <T extends object, TPath extends (DotPaths<T> | '')>(state: T, path: TPath) => TPath extends PathIndexingArray<Index> ? never : TPath extends PathIndexingArray<number> ? ValueInDotPath<T, TPath> | undefined : ValueInDotPath<T, TPath>;
40
+ /**
41
+ * Returns the value from a given dot path of an object/array.
42
+ * Returns undefined if the provided path doesnt exist.
43
+ */
44
+ declare const select: Select;
45
+
46
+ type SplitDotPathAtLastKey = <T extends string>(dotPath: T) => [string, string];
47
+ /**
48
+ * Splits string dotPath into ID and RemainingPath
49
+ */
50
+ declare const splitPathAtLastKey: SplitDotPathAtLastKey;
51
+
52
+ type Spread = <T extends object>(value: T, update: T extends Array<infer U> ? Array<U> : Partial<T>) => T;
53
+ /**
54
+ * Spreads if its an object or array to the target, if its not then returns same value
55
+ */
56
+ declare const spread: Spread;
57
+
58
+ type Set = <T>(newValue: T) => (value: T) => T;
59
+ /**
60
+ * Allows to set strongly typed values (removing inacurate "undefined" inference) in nested values inside arrays
61
+ */
62
+ declare const set: Set;
63
+
64
+ type SemiStrictMode = 'skip-non-existent-paths';
65
+ type NonStrictMode = 'implement-non-existent-paths';
66
+ type UpdateImmutably = {
67
+ <T extends object>(state: T, updates: DotPathUpdateObject<T>): T;
68
+ };
69
+ /**
70
+ * Creates a new updated object/array applying the changes provided in the update object.
71
+ * It doesnt modify the original input.
72
+ * If any of the paths doesnt exists it returns
73
+ */
74
+ declare const updateImmutably: UpdateImmutably;
75
+ type PosibleExpandedProps<T> = {
76
+ [K in keyof T]?: T[K] extends object ? PosibleExpandedProps<T[K]> & Record<any, any> : T[K];
77
+ };
78
+ type UpdateImmutablyNonStrictly = {
79
+ <T extends object>(state: T, updates: DotPathUpdateObject<T>, mode: SemiStrictMode): T;
80
+ <T extends object>(state: T, updates: DotPathUpdateObject<T>, mode: NonStrictMode): PosibleExpandedProps<T>;
81
+ };
82
+ /**
83
+ * Creates a new updated object/array applying the changes provided in the update object.
84
+ * It doesnt modify the original input.
85
+ * If any of the paths doesnt exists it adds it if possible.
86
+ */
87
+ declare const updateImmutablyAllowingNewProps: UpdateImmutablyNonStrictly;
88
+
89
+ export { type DotPathUpdateObject, type DotPaths, type DotPathsIncludingLength, type ValueInDotPath, remove, select, set, splitPathAtLastKey, spread, updateImmutably, updateImmutablyAllowingNewProps };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var u=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var D=(t,e)=>{for(var o in e)u(t,o,{get:e[o],enumerable:!0})},w=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of S(e))!j.call(t,a)&&a!==o&&u(t,a,{get:()=>e[a],enumerable:!(n=I(e,a))||n.enumerable});return t};var K=t=>w(u({},"__esModule",{value:!0}),t);var g={};D(g,{remove:()=>h,select:()=>f,set:()=>x,splitPathAtLastKey:()=>m,spread:()=>T,updateImmutably:()=>P,updateImmutablyAllowingNewProps:()=>A});module.exports=K(g);var h=(t,e)=>{if(!Array.isArray(t)&&t?.constructor!==Object)throw'Wrong type provided in "remove" function';let o=Array.isArray(e)?e:[e];if(Array.isArray(t)){let a=Symbol(),p=[...t];return o.forEach(i=>{p[i]=a}),p.filter(i=>i!==a)}let n={...t};return o.forEach(a=>delete n[a]),n};var f=(t,e)=>!e||typeof e!="string"?t:e.split(".").reduce((o,n)=>{if(o?.hasOwnProperty(n))return o[n]},t);var m=t=>{if(typeof t!="string")throw new Error(`Wrong dotPath type: ${t}`);let e=t.lastIndexOf(".")+1,o=e?t.slice(0,e-1):"",n=t.slice(e);return[o,n]};var T=(t,e)=>t?.constructor===Object&&e?.constructor===Object?{...t,...e}:Array.isArray(t)&&Array.isArray(e)?[...t,...e]:t;var x=t=>()=>t;var b=(t,e,o="strict-paths")=>{if(t?.constructor!==Object&&!Array.isArray(t))throw new Error(`${t} is not an object/array so cant be updated immutably`);if(!e)return t;let n=Array.isArray(t)?[...t]:{...t},a={};for(let[p,l]of Object.entries(e)){if(!p||p==="false"||p==="undefined"||p==="null")continue;let i=p.split("."),y=i.pop(),c=a,s=n;for(let r of i){if(!s[r]||typeof s[r]!="object"||s[r].constructor!==Object&&!Array.isArray(s[r]))throw new Error(`Invalid path provided: "${r}" is not an object/array in "${p}"`);c[r]||(s[r]=Array.isArray(s[r])?[...s[r]]:{...s[r]},c[r]={}),s=s[r],c=c[r]}let d=s;if(o!=="implement-non-existent-paths"){let r=o==="skip-non-existent-paths";if(Array.isArray(d)&&!(y<d.length)){if(r)continue;throw new Error(`Use spread to add indexes in ${i.join(".")}, because index ${y} doesnt exist in ${y}`)}if(!d.hasOwnProperty(y)){if(r)continue;throw new Error(`Property ${y} doesnt exist in the path ${i.join(".")} because its current value is: ${d}`)}}d[y]=typeof l=="function"?l(d[y]):l,delete c[y]}return n},P=b,A=b;0&&(module.exports={remove,select,set,splitPathAtLastKey,spread,updateImmutably,updateImmutablyAllowingNewProps});
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ var h=(t,e)=>{if(!Array.isArray(t)&&t?.constructor!==Object)throw'Wrong type provided in "remove" function';let n=Array.isArray(e)?e:[e];if(Array.isArray(t)){let y=Symbol(),s=[...t];return n.forEach(p=>{s[p]=y}),s.filter(p=>p!==y)}let a={...t};return n.forEach(y=>delete a[y]),a};var f=(t,e)=>!e||typeof e!="string"?t:e.split(".").reduce((n,a)=>{if(n?.hasOwnProperty(a))return n[a]},t);var m=t=>{if(typeof t!="string")throw new Error(`Wrong dotPath type: ${t}`);let e=t.lastIndexOf(".")+1,n=e?t.slice(0,e-1):"",a=t.slice(e);return[n,a]};var T=(t,e)=>t?.constructor===Object&&e?.constructor===Object?{...t,...e}:Array.isArray(t)&&Array.isArray(e)?[...t,...e]:t;var x=t=>()=>t;var u=(t,e,n="strict-paths")=>{if(t?.constructor!==Object&&!Array.isArray(t))throw new Error(`${t} is not an object/array so cant be updated immutably`);if(!e)return t;let a=Array.isArray(t)?[...t]:{...t},y={};for(let[s,l]of Object.entries(e)){if(!s||s==="false"||s==="undefined"||s==="null")continue;let p=s.split("."),i=p.pop(),c=y,o=a;for(let r of p){if(!o[r]||typeof o[r]!="object"||o[r].constructor!==Object&&!Array.isArray(o[r]))throw new Error(`Invalid path provided: "${r}" is not an object/array in "${s}"`);c[r]||(o[r]=Array.isArray(o[r])?[...o[r]]:{...o[r]},c[r]={}),o=o[r],c=c[r]}let d=o;if(n!=="implement-non-existent-paths"){let r=n==="skip-non-existent-paths";if(Array.isArray(d)&&!(i<d.length)){if(r)continue;throw new Error(`Use spread to add indexes in ${p.join(".")}, because index ${i} doesnt exist in ${i}`)}if(!d.hasOwnProperty(i)){if(r)continue;throw new Error(`Property ${i} doesnt exist in the path ${p.join(".")} because its current value is: ${d}`)}}d[i]=typeof l=="function"?l(d[i]):l,delete c[i]}return a},b=u,P=u;export{h as remove,f as select,x as set,m as splitPathAtLastKey,T as spread,b as updateImmutably,P as updateImmutablyAllowingNewProps};
package/package.json CHANGED
@@ -1,16 +1,44 @@
1
1
  {
2
- "name": "maraj",
3
- "version": "1.1.2",
4
- "description": "A lightweight 500 bytes gzipped alternative for immutable updates while dealing with objects and arrays",
5
- "main": "maraj.js",
6
- "type": "module",
7
- "scripts": {
8
- "test": "vitest"
9
- },
10
- "author": "Lukasz Maraj",
11
- "license": "MIT",
12
- "devDependencies": {
13
- "typescript": "^4.9.5",
14
- "vitest": "^0.28.4"
15
- }
16
- }
2
+ "name": "maraj",
3
+ "version": "2.0.0",
4
+ "description": "A lightweight 500 bytes gzipped alternative for immutable updates while dealing with objects and arrays",
5
+ "keywords": [
6
+ "shallow",
7
+ "shallow copy",
8
+ "nested copy"
9
+ ],
10
+ "author": "Lukasz Maraj",
11
+ "license": "MIT",
12
+ "private": false,
13
+ "main": "dist/index.js",
14
+ "module": "dist/index.mjs",
15
+ "types": "dist/index.d.ts",
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "dev": "vitest",
23
+ "test": "vitest run",
24
+ "build": "tsup src/index.ts --minify --format cjs,esm --dts",
25
+ "lint": "tsc",
26
+ "ci": "npm run lint && npm run test && npm run build",
27
+ "release": "npm run lint && npm run test && npm run build && changeset publish"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/Lukasz17git/maraj.git"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/Lukasz17git/maraj/issues"
35
+ },
36
+ "homepage": "https://github.com/Lukasz17git/maraj#readme",
37
+ "devDependencies": {
38
+ "@changesets/cli": "^2.27.1",
39
+ "@microsoft/api-extractor": "^7.38.5",
40
+ "tsup": "^8.0.1",
41
+ "typescript": "^4.9.5",
42
+ "vitest": "^0.28.4"
43
+ }
44
+ }
package/maraj.d.ts DELETED
@@ -1,40 +0,0 @@
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 DELETED
@@ -1,99 +0,0 @@
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
- return undefined
82
- }, state)
83
- }
84
-
85
-
86
- /**
87
- * Splits string path into ID and RemainingPath
88
- * @param {string} path - Path separated by dots
89
- * @returns {id: string, remainingPath: string} - {id: string, remainingPath: string | ''}
90
- */
91
- // splits a string id path
92
- export const splitPath = (path) => {
93
- if (typeof path !== 'string') throw new Error(`Provided path is not a string ${path}`)
94
- const lastDot = path.lastIndexOf(".") + 1
95
- return {
96
- id: path.slice(lastDot),
97
- remainingPath: lastDot ? path.slice(0, lastDot - 1) : ''
98
- }
99
- }
package/tsconfig.json DELETED
@@ -1,104 +0,0 @@
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
- }