maraj 1.1.2 → 2.1.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,153 @@
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 fast lightweight utility for creating **immutable updates**. Full typescript support. Only 600 bytes gziped. Includes usefull utilities for manipulating updates (like remove, select).
5
+
6
+ ### Features
7
+
8
+ - Full typescript support.
9
+ - Correct type inference.
10
+ - Multiple updates at same time mantaining the order of execution.
11
+ - Functional updates.
12
+
13
+ **<u>For Typescript:</u>** in tsconfig.json set **"strictNullChecks"** and **"noUncheckedIndexedAccess"** to true for correct type inference of optional properties (so it can correctly differentiate between optional props and props with possible undefined value)
14
+
15
+ ```ts
16
+ const originalValue = { name: 'one', lastname: 'two' modified: false, files: [{ filename: 'one' }] }
17
+
18
+ const updatedValue = updateImmutably(orignalValue, {
19
+ 'name': 'updated',
20
+ 'modified': (value, fullObject) => !value,
21
+ 'files.0.filename': 'zero',
22
+ })
23
+
24
+ // updatedValue = { name: 'updated', lastname: 'two' modified: true, files: [{ filename: 'zero' }] }
25
+
26
+ originalValue.files[1] === updatedValue.files[1] // true
27
+ ```
28
+
29
+ ### Limitations
30
+
31
+ - If "addNonExistentPropsAndIndexes" is enabled, numbers will always create an array if the array/object doesnt exist beforehand.
32
+
33
+ ```ts
34
+ const updatedValue = updateImmutably({}, {
35
+ 'files.1.name': 'new name',
36
+ }, true)
37
+ // updatedValue = { files: [<empty>, { name: 'new name' }] }
38
+ ```
39
+
40
+ - The type "UpdateDotObject" using computed properties ( [key] ) will always throw a ts error even if the typing is correct. [Playground simple explanation](https://www.typescriptlang.org/play?ts=5.3.2#code/LAKALgngDgpgBAGQJYGcxwLxwOQENtwA+cABgCQDeAdgK4C2ARjAE4C+JooksiqYASjADGAe2YATTHApwA2gGk4SKrzQBdAPwAuOItacQoqmjhDmMXGBiDREqQB4AKnBgAPK1XEpVYAHwAKAGsYCB1HAEpMX2lQODijE3MhHWQ0GzFJLApYuNyAejy4AD0wbxZmMR0UZSF4ADcAFgA6AGYmgFYldAB3JAAbPrgwAAsK7rhcFXKxCfQhYeFA5QBzUxE6KBorSWCIb0nJOtw+mhhvGmqqVasNvst4PqQrZmOyupgVJAAzIYWh6BWSm8tiSYByuTkuzUOl24P0IFy5jANGYKiSoFYQA)
41
+
42
+ ```ts
43
+ const updateFieldStore = <TPath extends DotPaths<Store>>(
44
+ path: TPath,
45
+ newValue: UpdateDotPathValue<Store, TPath>
46
+ ) => {
47
+ const update: UpdateDotPathObject<Store> = {
48
+ // ^throws ts error even if the typing is correct
49
+ [path]: newValue
50
+ } // fix: coherce it with " as UpdateDotPathObject<Store>"
51
+ return update
52
+ }
53
+ ```
54
+
55
+ - Use the "set" utility if typescript doesn't distinguish properly _"an optional field"_ vs a _"field which can have 'undefined' as type"_. Usually happens in optional nested props inside arrays.
56
+
57
+ ```ts
58
+ const updatedValue = updateImmutably(data, {
59
+ 'files.0.optionalProperty': 'new name',
60
+ 'files.1.optionalProperty': undefined, //no ts error
61
+ 'files.0.optionalProperty': set('new name'),
62
+ 'files.1.optionalProperty': set(undefined), //throws ts error, undefined cant be a value.
63
+ })
64
+ ```
65
+
66
+ ## Creating an Immutable Update
67
+
68
+ Arguments:
69
+
70
+ - Original Object
71
+ - Update Object
72
+ - If it should add non-existent properties/indexes
73
+
74
+ ## Example
75
+
76
+ ```js
77
+ import { updateImmutably } from "maraj";
78
+
79
+ const data = {
80
+ profile: { name: "Lukasz" },
81
+ works: ["soum", "fi"],
82
+ history: [
83
+ { title: "soum", size: 90, available: true, info: ["info1"] },
84
+ { title: "fi", size: 30, available: false, info: ["infoA"] },
85
+ ]
86
+ }
87
+
88
+ const newUpdatedObject = updateImmutably(data, {
89
+ "profile.age": 28, //add new properties if "addNonExistentPropsAndIndexes" is enabled
90
+ "profile.name": "Lucas", //update values
91
+ "works.1": "gs", //nested array update
92
+ "history.1.available": (currentValue) => (!currentValue), //functional update
93
+ "works": (v) => [...v, 'portfolio'] //add new value to array
94
+ })
95
+ ```
96
+
97
+ ## Remove Utility
98
+
99
+ Removes the **key of an object** or the **index of an array** in the key provided in the **updateImmutably.**
100
+
101
+ ```js
102
+ import {remove} from 'maraj'
103
+
104
+ const newUpdatedObject = updateImmutably(person,{
105
+ 'profile': (value) => remove(value, 'name'), // returns new value without the "name" prop
106
+ 'works': (value) => remove(value, 1), // returns new array without the provided index (1)
107
+ 'works': (value) => remove(value, [1, "0"]), // returns new array without the provided index (0,1)
108
+ })
109
+ ```
110
+
111
+ ## Select Utility
112
+
113
+ Selects the value of an object/array from a string-dot-path. Usefull in state management libraries.
114
+
115
+ ```js
116
+ import {select} from 'maraj'
117
+
118
+ const stringPath = 'works.1.size'
119
+
120
+ const work1SizeSelector = (state) => select(state, stringPath) // will behave as (store) => store[works][1][size]
121
+ ```
122
+
123
+ ## SplitPathAtLastKey Utility
124
+
125
+ Usefull when you want to retrieve the last key (for example an id).
126
+
127
+ Splits string path (example:'projects.1.data.size' ) into two:
128
+
129
+ - remainingPath: the remaining path (in this case 'projects.1.data')
130
+ - lastKey: the last key in the path (in this case 'size')
131
+
132
+ ```js
133
+ import { splitPathAtLastKey } from 'maraj'
134
+
135
+ const stringPath = 'works.1.size'
136
+
137
+ const [remainingPath, last] = splitPathAtLastKey(stringPath)
138
+ // last = 'size'
139
+ // remainingPath = 'works.1'
140
+ ```
141
+
142
+ ## Set Utility
143
+
144
+ In some unusual cases (usually when updating an optional object prop inside an array) typescript infers incorrectly the optional key vs a key with undefined value. To fix this typing issue, use the "set" function so it correctly infers the type in the field.
145
+
146
+ ```ts
147
+ const updatedValue = updateImmutably(data, {
148
+ 'files.0.optionalProperty': 'new name',
149
+ 'files.1.optionalProperty': undefined, //no ts error
150
+ 'files.0.optionalProperty': set('new name'),
151
+ 'files.1.optionalProperty': set(undefined), //throws ts error, undefined cant be a value.
152
+ })
153
+ ```
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Paths implementation
3
+ */
4
+ type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
5
+ type IsTuple<T extends ReadonlyArray<any>> = number extends T['length'] ? false : true;
6
+ type Index = '_INDEX_';
7
+ type ArrayIndexPaths = `${number}` | Index;
8
+ type ArrayPaths<TInnerType> = `${ArrayIndexPaths}` | `${ArrayIndexPaths}.${Flatten<TInnerType>}`;
9
+ type ObjectPaths<T> = {
10
+ [Key in keyof T & string]: `${Key}` | `${Key}.${Flatten<T[Key]>}`;
11
+ }[keyof T & string];
12
+ type TuplePaths<T> = ObjectPaths<Omit<T, keyof any[]>>;
13
+ type Flatten<T> = T extends ReadonlyArray<infer U> ? IsTuple<T> extends true ? TuplePaths<T> : ArrayPaths<U> : T extends PrimitivesAndNativeObjects ? never : ObjectPaths<T>;
14
+ type DotPaths<T extends object> = Flatten<T>;
15
+ /**
16
+ * Type to know when a path is indexing an array
17
+ */
18
+ type PathIndexingArray<T extends string | number> = `${T}` | `${T}.${string}` | `${string}.${T}` | `${string}.${T}.${string}`;
19
+ /**
20
+ * Nested Property Type implementation
21
+ */
22
+ 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;
23
+ type ValueInDotPath<TObject extends object, TPath extends DotPaths<TObject> | ''> = NestedProperty<TObject, TPath>;
24
+ type DotPathUpdateValue<TObject extends object, TPath extends DotPaths<TObject>> = TPath extends PathIndexingArray<Index> ? [`PATH ERROR: replace _INDEX_ with a NUMBER`, ValueInDotPath<TObject, TPath>, ((fieldValue: ValueInDotPath<TObject, TPath>, fullObject: TObject) => ValueInDotPath<TObject, TPath>)] : ValueInDotPath<TObject, TPath> | ((fieldValue: ValueInDotPath<TObject, TPath>, fullObject: TObject) => ValueInDotPath<TObject, TPath>);
25
+ /**
26
+ * Update Object Type Implementation
27
+ */
28
+ type DotPathUpdateObject<TObject extends object> = {
29
+ [TKey in DotPaths<TObject>]?: DotPathUpdateValue<TObject, TKey>;
30
+ };
31
+ /**
32
+ * Optional and Required keys
33
+ */
34
+ type NonPartialKeys = string | number | boolean | symbol | bigint | null | object;
35
+ type OptionalKeys<T> = {
36
+ [K in keyof T & string]: T[K] extends NonPartialKeys ? never : K;
37
+ }[keyof T & string];
38
+ type RequiredKeys<T> = {
39
+ [K in keyof T & string]: T[K] extends NonPartialKeys ? K : never;
40
+ }[keyof T & string];
41
+
42
+ type Remove = <T extends object>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : (OptionalKeys<T> | (OptionalKeys<T>)[])) => T;
43
+ /**
44
+ * Removes properties or indexes, order doesn't matter.
45
+ */
46
+ declare const remove: Remove;
47
+
48
+ 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>;
49
+ /**
50
+ * Returns the value from a given dot path of an object/array.
51
+ * Returns undefined if the provided path doesnt exist.
52
+ */
53
+ declare const select: Select;
54
+
55
+ type SplitDotPathAtLastKey = <T extends string>(dotPath: T) => [string, string];
56
+ /**
57
+ * Splits string dotPath into ID and RemainingPath
58
+ */
59
+ declare const splitPathAtLastKey: SplitDotPathAtLastKey;
60
+
61
+ type Set = <T>(newValue: T) => (value: T) => T;
62
+ /**
63
+ * Allows to set strongly typed values (removing inacurate "undefined" inference) in nested values inside arrays
64
+ */
65
+ declare const set: Set;
66
+
67
+ type UpdateImmutably = <T extends object>(state: T, updates: DotPathUpdateObject<T>, addNonExistentPropsAndIndexes?: true) => T;
68
+ /**
69
+ * Creates a new updated object/array applying the changes provided in the update object.
70
+ * It doesnt modify the original input.
71
+ * If any of the paths doesnt exists it returns
72
+ */
73
+ declare const updateImmutably: UpdateImmutably;
74
+
75
+ export { type DotPathUpdateObject, type DotPathUpdateValue, type DotPaths, type OptionalKeys, type RequiredKeys, type ValueInDotPath, remove, select, set, splitPathAtLastKey, updateImmutably };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Paths implementation
3
+ */
4
+ type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
5
+ type IsTuple<T extends ReadonlyArray<any>> = number extends T['length'] ? false : true;
6
+ type Index = '_INDEX_';
7
+ type ArrayIndexPaths = `${number}` | Index;
8
+ type ArrayPaths<TInnerType> = `${ArrayIndexPaths}` | `${ArrayIndexPaths}.${Flatten<TInnerType>}`;
9
+ type ObjectPaths<T> = {
10
+ [Key in keyof T & string]: `${Key}` | `${Key}.${Flatten<T[Key]>}`;
11
+ }[keyof T & string];
12
+ type TuplePaths<T> = ObjectPaths<Omit<T, keyof any[]>>;
13
+ type Flatten<T> = T extends ReadonlyArray<infer U> ? IsTuple<T> extends true ? TuplePaths<T> : ArrayPaths<U> : T extends PrimitivesAndNativeObjects ? never : ObjectPaths<T>;
14
+ type DotPaths<T extends object> = Flatten<T>;
15
+ /**
16
+ * Type to know when a path is indexing an array
17
+ */
18
+ type PathIndexingArray<T extends string | number> = `${T}` | `${T}.${string}` | `${string}.${T}` | `${string}.${T}.${string}`;
19
+ /**
20
+ * Nested Property Type implementation
21
+ */
22
+ 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;
23
+ type ValueInDotPath<TObject extends object, TPath extends DotPaths<TObject> | ''> = NestedProperty<TObject, TPath>;
24
+ type DotPathUpdateValue<TObject extends object, TPath extends DotPaths<TObject>> = TPath extends PathIndexingArray<Index> ? [`PATH ERROR: replace _INDEX_ with a NUMBER`, ValueInDotPath<TObject, TPath>, ((fieldValue: ValueInDotPath<TObject, TPath>, fullObject: TObject) => ValueInDotPath<TObject, TPath>)] : ValueInDotPath<TObject, TPath> | ((fieldValue: ValueInDotPath<TObject, TPath>, fullObject: TObject) => ValueInDotPath<TObject, TPath>);
25
+ /**
26
+ * Update Object Type Implementation
27
+ */
28
+ type DotPathUpdateObject<TObject extends object> = {
29
+ [TKey in DotPaths<TObject>]?: DotPathUpdateValue<TObject, TKey>;
30
+ };
31
+ /**
32
+ * Optional and Required keys
33
+ */
34
+ type NonPartialKeys = string | number | boolean | symbol | bigint | null | object;
35
+ type OptionalKeys<T> = {
36
+ [K in keyof T & string]: T[K] extends NonPartialKeys ? never : K;
37
+ }[keyof T & string];
38
+ type RequiredKeys<T> = {
39
+ [K in keyof T & string]: T[K] extends NonPartialKeys ? K : never;
40
+ }[keyof T & string];
41
+
42
+ type Remove = <T extends object>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : (OptionalKeys<T> | (OptionalKeys<T>)[])) => T;
43
+ /**
44
+ * Removes properties or indexes, order doesn't matter.
45
+ */
46
+ declare const remove: Remove;
47
+
48
+ 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>;
49
+ /**
50
+ * Returns the value from a given dot path of an object/array.
51
+ * Returns undefined if the provided path doesnt exist.
52
+ */
53
+ declare const select: Select;
54
+
55
+ type SplitDotPathAtLastKey = <T extends string>(dotPath: T) => [string, string];
56
+ /**
57
+ * Splits string dotPath into ID and RemainingPath
58
+ */
59
+ declare const splitPathAtLastKey: SplitDotPathAtLastKey;
60
+
61
+ type Set = <T>(newValue: T) => (value: T) => T;
62
+ /**
63
+ * Allows to set strongly typed values (removing inacurate "undefined" inference) in nested values inside arrays
64
+ */
65
+ declare const set: Set;
66
+
67
+ type UpdateImmutably = <T extends object>(state: T, updates: DotPathUpdateObject<T>, addNonExistentPropsAndIndexes?: true) => T;
68
+ /**
69
+ * Creates a new updated object/array applying the changes provided in the update object.
70
+ * It doesnt modify the original input.
71
+ * If any of the paths doesnt exists it returns
72
+ */
73
+ declare const updateImmutably: UpdateImmutably;
74
+
75
+ export { type DotPathUpdateObject, type DotPathUpdateValue, type DotPaths, type OptionalKeys, type RequiredKeys, type ValueInDotPath, remove, select, set, splitPathAtLastKey, updateImmutably };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var f=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var j=(t,e)=>{for(var r in e)f(t,r,{get:e[r],enumerable:!0})},O=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of D(e))!w.call(t,a)&&a!==r&&f(t,a,{get:()=>e[a],enumerable:!(o=K(e,a))||o.enumerable});return t};var g=t=>O(f({},"__esModule",{value:!0}),t);var v={};j(v,{remove:()=>P,select:()=>T,set:()=>b,splitPathAtLastKey:()=>m,updateImmutably:()=>A});module.exports=g(v);var P=(t,e)=>{if(!Array.isArray(t)&&t?.constructor!==Object)throw'Wrong type provided in "remove" function';let r=Array.isArray(e)?e:[e];if(Array.isArray(t)){let a=Symbol(),y=[...t];return r.forEach(n=>{y[n]=a}),y.filter(n=>n!==a)}let o={...t};return r.forEach(a=>delete o[a]),o};var T=(t,e)=>!e||typeof e!="string"?t:e.split(".").reduce((r,o)=>{if(r?.hasOwnProperty(o))return r[o]},t);var m=t=>{if(typeof t!="string")throw new Error(`Wrong dotPath type: ${t}`);let e=t.lastIndexOf(".")+1,r=e?t.slice(0,e-1):"",o=t.slice(e);return[r,o]};var b=t=>()=>t;var A=(t,e,r)=>{if(t?.constructor!==Object&&!Array.isArray(t))throw new Error(`${t} is not an object/array`);if(!e)return t;let o=Array.isArray(t)?[...t]:{...t},a={};for(let[y,h]of Object.entries(e)){if(!y)continue;let n=y.split("."),s=n.pop(),l=a,d=o;for(let u=0;u<n.length;u++){let i=n[u],p=d[i],I=typeof p=="object"&&(p.constructor===Object||Array.isArray(p)),x=r&&p===void 0;if(!I&&!x)throw new Error(`Invalid path provided: "${i}" is not an object/array in "${y}"`);l[i]||(x?d[i]=isNaN(n[u+1]??s)?{}:[]:d[i]=Array.isArray(p)?[...p]:{...p},l[i]={}),d=d[i],l=l[i]}let c=d;if(!r){if(Array.isArray(c)&&!(s<c.length))throw new Error(`Index ${s} doesnt exist in the path ${n.join(".")} because its value is ${s}, use spread operator for adding new indexes`);if(!c.hasOwnProperty(s))throw new Error(`Property ${s} doesnt exist in the path ${n.join(".")} because its value is ${c}`)}c[s]=typeof h=="function"?h(c[s],o):h,delete l[s]}return o};0&&(module.exports={remove,select,set,splitPathAtLastKey,updateImmutably});
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ var P=(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 p=Symbol(),y=[...t];return o.forEach(a=>{y[a]=p}),y.filter(a=>a!==p)}let r={...t};return o.forEach(p=>delete r[p]),r};var T=(t,e)=>!e||typeof e!="string"?t:e.split(".").reduce((o,r)=>{if(o?.hasOwnProperty(r))return o[r]},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):"",r=t.slice(e);return[o,r]};var b=t=>()=>t;var A=(t,e,o)=>{if(t?.constructor!==Object&&!Array.isArray(t))throw new Error(`${t} is not an object/array`);if(!e)return t;let r=Array.isArray(t)?[...t]:{...t},p={};for(let[y,h]of Object.entries(e)){if(!y)continue;let a=y.split("."),n=a.pop(),l=p,d=r;for(let u=0;u<a.length;u++){let s=a[u],i=d[s],x=typeof i=="object"&&(i.constructor===Object||Array.isArray(i)),f=o&&i===void 0;if(!x&&!f)throw new Error(`Invalid path provided: "${s}" is not an object/array in "${y}"`);l[s]||(f?d[s]=isNaN(a[u+1]??n)?{}:[]:d[s]=Array.isArray(i)?[...i]:{...i},l[s]={}),d=d[s],l=l[s]}let c=d;if(!o){if(Array.isArray(c)&&!(n<c.length))throw new Error(`Index ${n} doesnt exist in the path ${a.join(".")} because its value is ${n}, use spread operator for adding new indexes`);if(!c.hasOwnProperty(n))throw new Error(`Property ${n} doesnt exist in the path ${a.join(".")} because its value is ${c}`)}c[n]=typeof h=="function"?h(c[n],r):h,delete l[n]}return r};export{P as remove,T as select,b as set,m as splitPathAtLastKey,A as updateImmutably};
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.1.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": "^5.3.3",
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
- }