maraj 2.4.1 → 2.5.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,16 +1,18 @@
1
1
 
2
2
  # Maraj
3
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).
4
+ A fast lightweight utility for creating **immutable updates**. Fully typed. Only 600 bytes gziped. Includes usefull utilities for manipulating updates (like remove, select).
5
5
 
6
6
  ### Features
7
7
 
8
+ - updateImmutably and modifyImmutably.
8
9
  - Full typescript support.
9
10
  - Correct type inference.
10
- - Multiple updates at same time mantaining the order of execution.
11
+ - Multiple and concurrent updates.
11
12
  - Functional updates.
13
+ - Includes usefull utilities like "remove", "select".
12
14
 
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)
15
+ **<u>_For Typescript:_</u>** in tsconfig.json set **"strictNullChecks"** and **"noUncheckedIndexedAccess"** to **true** to be able to infer correctly the type of optional properties and properties with posible undefined value. ({key?: ''} !== {key: '' | undefined})
14
16
 
15
17
  ```ts
16
18
  const originalValue = { name: 'one', lastname: 'two' modified: false, files: [{ filename: 'one' }] }
@@ -20,24 +22,36 @@ const updatedValue = updateImmutably(orignalValue, {
20
22
  'modified': (value, fullObject) => !value,
21
23
  'files.0.filename': 'zero',
22
24
  })
23
-
24
25
  // updatedValue = { name: 'updated', lastname: 'two' modified: true, files: [{ filename: 'zero' }] }
25
-
26
26
  originalValue.files[1] === updatedValue.files[1] // true
27
+
28
+ const newValue = modifyImmutably(orignalValue, {
29
+ 'newProp': 'new',
30
+ 'data.0.name': 'dataName'
31
+ })
32
+ // updatedValue = { ... , newProp: 'new', data: [{ name: 'dataName' }] }
33
+ originalValue.files[1] === newValue.files[1] // true
27
34
  ```
28
35
 
29
36
  ### Limitations
30
37
 
31
- - If "addNonExistentPropsAndIndexes" is enabled, numbers will always create an array if the array/object doesnt exist beforehand.
38
+ - In "modifyImmutably", **numbers** inside path will **always** create an **array** if the array/object doesnt exist beforehand. If you want an object instead of an array, add it beforehand.
32
39
 
33
40
  ```ts
34
- const updatedValue = updateImmutably({}, {
41
+ const updatedValue = modifyImmutably({}, {
35
42
  'files.1.name': 'new name',
36
- }, true)
37
- // updatedValue = { files: [<empty>, { name: 'new name' }] }
43
+ })
44
+ // The "files" prop is an array. updatedValue = { files: [<empty>, { name: 'new name' }] }
45
+
46
+ // To get an object instead of an array create an object beforehand
47
+ const updatedValue2 = modifyImmutably({}, {
48
+ 'files': {}, // add an object first, so then i can add props as numbers after it
49
+ 'files.1.name': 'new name',
50
+ })
51
+ // updatedValue2 = { files: { '1': { name: 'new name' } } }
38
52
  ```
39
53
 
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)
54
+ - The type "UpdateDotPathObject" (the type used as second parameter in the updateImmutably function) if used to create new update objects using computed properties { [key]: value } 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
55
 
42
56
  ```ts
43
57
  const updateFieldStore = <TPath extends DotPaths<Store>>(
@@ -52,24 +66,23 @@ const updateFieldStore = <TPath extends DotPaths<Store>>(
52
66
  }
53
67
  ```
54
68
 
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.
69
+ - Use the "set" utility if typescript doesn't infer properly _"an optional field"_ vs a _"field which can have 'undefined' as type"_. Usually happens in optional nested props inside arrays.
56
70
 
57
71
  ```ts
58
72
  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.
73
+ 'files.0.nonOptionalProperty': 'new name',
74
+ 'files.1.nonOptionalProperty': undefined, //no ts error
75
+ 'files.0.nonOptionalProperty': set('new name'),
76
+ 'files.1.nonOptionalProperty': set(undefined), //throws ts error, undefined cant be a value.
63
77
  })
64
78
  ```
65
79
 
66
- ## Creating an Immutable Update
80
+ ## Creating a Strict Immutable Update
67
81
 
68
82
  Arguments:
69
83
 
70
84
  - Original Object
71
85
  - Update Object
72
- - If it should add non-existent properties/indexes
73
86
 
74
87
  ## Example
75
88
 
@@ -86,7 +99,6 @@ const data = {
86
99
  }
87
100
 
88
101
  const newUpdatedObject = updateImmutably(data, {
89
- "profile.age": 28, //add new properties if "addNonExistentPropsAndIndexes" is enabled
90
102
  "profile.name": "Lucas", //update values
91
103
  "works.1": "gs", //nested array update
92
104
  "history.1.available": (currentValue) => (!currentValue), //functional update
@@ -94,6 +106,34 @@ const newUpdatedObject = updateImmutably(data, {
94
106
  })
95
107
  ```
96
108
 
109
+ ## Creating an Immutable Update allowing new props to be added
110
+
111
+ Arguments:
112
+
113
+ - Original Object
114
+ - Update Object
115
+
116
+ ## Example
117
+
118
+ ```js
119
+ import { modifyImmutably } from "maraj";
120
+
121
+ const data = {
122
+ profile: { name: "Lukasz" },
123
+ works: ["soum", "fi"],
124
+ history: [
125
+ { title: "soum", size: 90, available: true, info: ["info1"] },
126
+ { title: "fi", size: 30, available: false, info: ["infoA"] },
127
+ ]
128
+ }
129
+
130
+ const newUpdatedObject = modifyImmutably(data, {
131
+ "profile.age": 28, //add new property
132
+ "profile.name": "Lucas", //update values
133
+ "works.10": "gs", //increases the array (filling it up with empty/undefined) and sets the value in the index of 10 to "gs"
134
+ })
135
+ ```
136
+
97
137
  ## Remove Utility
98
138
 
99
139
  Removes the **key of an object** or the **index of an array** in the key provided in the **updateImmutably.**
@@ -103,8 +143,9 @@ import {remove} from 'maraj'
103
143
 
104
144
  const newUpdatedObject = updateImmutably(person,{
105
145
  'profile': (value) => remove(value, 'name'), // returns new value without the "name" prop
146
+ 'profile': (value) => remove(value, ['name', 'lastname']), // returns new value without the "name" and "lastname" prop
106
147
  '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)
148
+ 'works': (value) => remove(value, [1, "0"]), // returns new array without the provided index "0" and "1"
108
149
  })
109
150
  ```
110
151
 
@@ -134,8 +175,8 @@ import { splitPathAtLastKey } from 'maraj'
134
175
 
135
176
  const stringPath = 'works.1.size'
136
177
 
137
- const [remainingPath, last] = splitPathAtLastKey(stringPath)
138
- // last = 'size'
178
+ const [remainingPath, lastKey] = splitPathAtLastKey(stringPath)
179
+ // lastKey = 'size'
139
180
  // remainingPath = 'works.1'
140
181
  ```
141
182
 
package/dist/index.d.mts CHANGED
@@ -1,3 +1,25 @@
1
+ /** Index literal type to improve DX at managing updates. */
2
+ declare const LITERAL_INDEX = "${number}";
3
+ type LiteralIndex = typeof LITERAL_INDEX;
4
+ type UpdateImmutably = <T extends object>(state: T, updates: DotPathUpdateObject<T>) => T;
5
+ /**
6
+ * Creates a new object applying strict immutable updates using dot-path syntax. Can't add new props or indexes.
7
+ * @param state Original State Object.
8
+ * @param updates Dot Path Update Object.
9
+ * @param addNonExistentPropsAndIndexes If it should or not create non-existent fields.
10
+ * @returns New Updated Object.
11
+ */
12
+ declare const updateImmutably: UpdateImmutably;
13
+ type ModifyImmutably = <T extends object>(state: T, updates: DotPathUpdateObject<T> | Record<string, any>) => T;
14
+ /**
15
+ * Creates a new object applying immutable modifications using dot-path syntax. It will add non-existent props or indexes if provided.
16
+ * @param state Original State Object.
17
+ * @param updates Dot Path Update Object.
18
+ * @param addNonExistentPropsAndIndexes If it should or not create non-existent fields.
19
+ * @returns New Updated Object.
20
+ */
21
+ declare const modifyImmutably: ModifyImmutably;
22
+
1
23
  /**
2
24
  * --------------------------------------------
3
25
  * UTILITIES
@@ -5,10 +27,8 @@
5
27
  */
6
28
  /** Primitives and browser native objects. */
7
29
  type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
8
- /** Index literal type to improve DX at managing updates. */
9
- type LiteralIndex = '${number}';
10
30
  /** Array indexes type. */
11
- type ArrayIndexes = `${number}` | LiteralIndex;
31
+ type ArrayIndexes = number | LiteralIndex;
12
32
  /** To check if a ReadonlyArray is a tuple or not. */
13
33
  type IsTuple<T extends ReadonlyArray<any>> = number extends T['length'] ? false : true;
14
34
  /**
@@ -60,18 +80,16 @@ type DotPathUpdateObject<TObject> = {
60
80
  * REQUIRED OR OPTIONAL KEYS
61
81
  * --------------------------------------------
62
82
  */
63
- /** All types instead of undefined. */
64
- type NonPartialKeys = null | object;
65
83
  /** Returns only the optional keys of an object. */
66
- type RetrieveOptionalKeys<T> = {
67
- [K in keyof T & string]: T[K] extends NonPartialKeys ? never : K;
68
- }[keyof T & string];
84
+ type OptionalKeys<T> = {
85
+ [K in keyof T]-?: {} extends Pick<T, K> ? K : never;
86
+ }[keyof T];
69
87
  /** Returns only the required keys of an object. */
70
- type RetrieveRequiredKeys<T> = {
71
- [K in keyof T & string]: T[K] extends NonPartialKeys ? K : never;
72
- }[keyof T & string];
88
+ type RequiredKeys<T> = {
89
+ [K in keyof T]-?: {} extends Pick<T, K> ? never : K;
90
+ }[keyof T];
73
91
 
74
- type Remove = <T extends object>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : (RetrieveOptionalKeys<T> | (RetrieveOptionalKeys<T>)[])) => T;
92
+ type Remove = <T extends object>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : OptionalKeys<T> | (OptionalKeys<T>)[]) => T;
75
93
  /**
76
94
  * Removes properties or indexes, order doesn't matter.
77
95
  * @param value Object/array from where to remove keys/indexes shallowly.
@@ -107,14 +125,10 @@ type Set = <T>(newValue: T) => (value: T) => T;
107
125
  */
108
126
  declare const set: Set;
109
127
 
110
- type UpdateImmutably = <T extends object>(state: T, updates: DotPathUpdateObject<T>, addNonExistentPropsAndIndexes?: true) => T;
111
- /**
112
- * Creates a new object applying immutable updates using dot-path syntax.
113
- * @param state Original State Object.
114
- * @param updates Dot Path Update Object.
115
- * @param addNonExistentPropsAndIndexes If it should or not create non-existent fields.
116
- * @returns New Updated Object.
117
- */
118
- declare const updateImmutably: UpdateImmutably;
128
+ /** Checks if any provided value is an object literal or not */
129
+ declare const isObjectLiteral: (valueToTest: any) => boolean;
130
+
131
+ declare const parseStringIndex: (v: string) => number | null;
132
+ declare const isStringIndex: (v: string) => boolean;
119
133
 
120
- export { type DotPathUpdateObject, type DotPathUpdateValue, type DotPaths, type PrimitivesAndNativeObjects, type RetrieveOptionalKeys, type RetrieveRequiredKeys, type ReturnedValueInDotPath, type ValueInDotPath, remove, select, set, splitPathAtLastKey, updateImmutably };
134
+ export { type DotPathUpdateObject, type DotPathUpdateValue, type DotPaths, type OptionalKeys, type PrimitivesAndNativeObjects, type RequiredKeys, type ReturnedValueInDotPath, type ValueInDotPath, isObjectLiteral, isStringIndex, modifyImmutably, parseStringIndex, remove, select, set, splitPathAtLastKey, updateImmutably };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,25 @@
1
+ /** Index literal type to improve DX at managing updates. */
2
+ declare const LITERAL_INDEX = "${number}";
3
+ type LiteralIndex = typeof LITERAL_INDEX;
4
+ type UpdateImmutably = <T extends object>(state: T, updates: DotPathUpdateObject<T>) => T;
5
+ /**
6
+ * Creates a new object applying strict immutable updates using dot-path syntax. Can't add new props or indexes.
7
+ * @param state Original State Object.
8
+ * @param updates Dot Path Update Object.
9
+ * @param addNonExistentPropsAndIndexes If it should or not create non-existent fields.
10
+ * @returns New Updated Object.
11
+ */
12
+ declare const updateImmutably: UpdateImmutably;
13
+ type ModifyImmutably = <T extends object>(state: T, updates: DotPathUpdateObject<T> | Record<string, any>) => T;
14
+ /**
15
+ * Creates a new object applying immutable modifications using dot-path syntax. It will add non-existent props or indexes if provided.
16
+ * @param state Original State Object.
17
+ * @param updates Dot Path Update Object.
18
+ * @param addNonExistentPropsAndIndexes If it should or not create non-existent fields.
19
+ * @returns New Updated Object.
20
+ */
21
+ declare const modifyImmutably: ModifyImmutably;
22
+
1
23
  /**
2
24
  * --------------------------------------------
3
25
  * UTILITIES
@@ -5,10 +27,8 @@
5
27
  */
6
28
  /** Primitives and browser native objects. */
7
29
  type PrimitivesAndNativeObjects = null | undefined | string | number | boolean | symbol | bigint | Date | FileList | File;
8
- /** Index literal type to improve DX at managing updates. */
9
- type LiteralIndex = '${number}';
10
30
  /** Array indexes type. */
11
- type ArrayIndexes = `${number}` | LiteralIndex;
31
+ type ArrayIndexes = number | LiteralIndex;
12
32
  /** To check if a ReadonlyArray is a tuple or not. */
13
33
  type IsTuple<T extends ReadonlyArray<any>> = number extends T['length'] ? false : true;
14
34
  /**
@@ -60,18 +80,16 @@ type DotPathUpdateObject<TObject> = {
60
80
  * REQUIRED OR OPTIONAL KEYS
61
81
  * --------------------------------------------
62
82
  */
63
- /** All types instead of undefined. */
64
- type NonPartialKeys = null | object;
65
83
  /** Returns only the optional keys of an object. */
66
- type RetrieveOptionalKeys<T> = {
67
- [K in keyof T & string]: T[K] extends NonPartialKeys ? never : K;
68
- }[keyof T & string];
84
+ type OptionalKeys<T> = {
85
+ [K in keyof T]-?: {} extends Pick<T, K> ? K : never;
86
+ }[keyof T];
69
87
  /** Returns only the required keys of an object. */
70
- type RetrieveRequiredKeys<T> = {
71
- [K in keyof T & string]: T[K] extends NonPartialKeys ? K : never;
72
- }[keyof T & string];
88
+ type RequiredKeys<T> = {
89
+ [K in keyof T]-?: {} extends Pick<T, K> ? never : K;
90
+ }[keyof T];
73
91
 
74
- type Remove = <T extends object>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : (RetrieveOptionalKeys<T> | (RetrieveOptionalKeys<T>)[])) => T;
92
+ type Remove = <T extends object>(value: T, keys: T extends any[] ? (number | `${number}` | (number | `${number}`)[]) : OptionalKeys<T> | (OptionalKeys<T>)[]) => T;
75
93
  /**
76
94
  * Removes properties or indexes, order doesn't matter.
77
95
  * @param value Object/array from where to remove keys/indexes shallowly.
@@ -107,14 +125,10 @@ type Set = <T>(newValue: T) => (value: T) => T;
107
125
  */
108
126
  declare const set: Set;
109
127
 
110
- type UpdateImmutably = <T extends object>(state: T, updates: DotPathUpdateObject<T>, addNonExistentPropsAndIndexes?: true) => T;
111
- /**
112
- * Creates a new object applying immutable updates using dot-path syntax.
113
- * @param state Original State Object.
114
- * @param updates Dot Path Update Object.
115
- * @param addNonExistentPropsAndIndexes If it should or not create non-existent fields.
116
- * @returns New Updated Object.
117
- */
118
- declare const updateImmutably: UpdateImmutably;
128
+ /** Checks if any provided value is an object literal or not */
129
+ declare const isObjectLiteral: (valueToTest: any) => boolean;
130
+
131
+ declare const parseStringIndex: (v: string) => number | null;
132
+ declare const isStringIndex: (v: string) => boolean;
119
133
 
120
- export { type DotPathUpdateObject, type DotPathUpdateValue, type DotPaths, type PrimitivesAndNativeObjects, type RetrieveOptionalKeys, type RetrieveRequiredKeys, type ReturnedValueInDotPath, type ValueInDotPath, remove, select, set, splitPathAtLastKey, updateImmutably };
134
+ export { type DotPathUpdateObject, type DotPathUpdateValue, type DotPaths, type OptionalKeys, type PrimitivesAndNativeObjects, type RequiredKeys, type ReturnedValueInDotPath, type ValueInDotPath, isObjectLiteral, isStringIndex, modifyImmutably, parseStringIndex, remove, select, set, splitPathAtLastKey, updateImmutably };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var D=(t,e)=>{for(var r in e)f(t,r,{get:e[r],enumerable:!0})},v=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of j(e))!w.call(t,a)&&a!==r&&f(t,a,{get:()=>e[a],enumerable:!(o=O(e,a))||o.enumerable});return t};var I=t=>v(f({},"__esModule",{value:!0}),t);var R={};D(R,{remove:()=>b,select:()=>T,set:()=>K,splitPathAtLastKey:()=>P,updateImmutably:()=>x});module.exports=I(R);var b=(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 P=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 K=t=>()=>t;var x=(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,d]of Object.entries(e)){if(!y)continue;let n=y.split("."),s=n.pop(),u=a,c=o;for(let h=0;h<n.length;h++){let i=n[h],p=c[i],A=typeof p=="object"&&(p.constructor===Object||Array.isArray(p)),m=r&&p===void 0;if(!A&&!m)throw new Error(`Invalid path provided: "${i}" is not an object/array in "${y}"`);u[i]||(m?c[i]=isNaN(n[h+1]??s)?{}:[]:c[i]=Array.isArray(p)?[...p]:{...p},u[i]={}),c=c[i],u=u[i]}let l=c;if(!r){if(Array.isArray(l)&&!(s<l.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(!l.hasOwnProperty(s))throw new Error(`Property ${s} doesnt exist in the path ${n.join(".")} because its value is ${l}`)}l[s]=typeof d=="function"?d(l[s],o):d,delete u[s]}return o};0&&(module.exports={remove,select,set,splitPathAtLastKey,updateImmutably});
1
+ "use strict";var b=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var R=(t,e)=>{for(var r in e)b(t,r,{get:e[r],enumerable:!0})},$=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of w(e))!E.call(t,n)&&n!==r&&b(t,n,{get:()=>e[n],enumerable:!(o=S(e,n))||o.enumerable});return t};var U=t=>$(b({},"__esModule",{value:!0}),t);var V={};R(V,{isObjectLiteral:()=>d,isStringIndex:()=>h,modifyImmutably:()=>D,parseStringIndex:()=>g,remove:()=>I,select:()=>T,set:()=>O,splitPathAtLastKey:()=>P,updateImmutably:()=>K});module.exports=U(V);var I=(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 n=Symbol(),p=[...t];return r.forEach(a=>{p[a]=n}),p.filter(a=>a!==n)}let o={...t};return r.forEach(n=>delete o[n]),o};var T=(t,e)=>!e||typeof e!="string"?t:e.split(".").reduce((r,o)=>{if(r?.hasOwnProperty(o))return r[o]},t);var P=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 O=t=>()=>t;var d=t=>!!t&&Object.getPrototypeOf(t)===Object.prototype;var g=t=>{let e=parseInt(t);return e.toString()===t?e:null},h=t=>parseInt(t).toString()===t;var A="${number}",j=(t,e,r)=>{if(!d(t)&&!Array.isArray(t))throw new Error(`"${t}" is not an literalObject/array`);if(!e)return t;let o=Array.isArray(t)?[...t]:{...t},n={};for(let[p,m]of Object.entries(e)){if(!p)continue;let a=p.split(".");if(a.includes(A))throw new Error(`"${A}" inside "${p}"`);let i=a.pop(),l=n,y=o;for(let u=0;u<a.length;u++){let s=a[u],c=y[s],L=d(c)||Array.isArray(c),x=r&&c===void 0;if(!L&&!x)throw new Error(`"${s}" doesnt exist in "${a.slice(0,u+1).join(".")}"`);l[s]||(x?y[s]=h(a[u+1]??i)?[]:{}:y[s]=Array.isArray(c)?[...c]:{...c},l[s]={}),y=y[s],l=l[s]}let f=y;if(!r&&!f.hasOwnProperty(i))throw new Error(`Property/Index "${i}" doesnt exist in the path "${a.join(".")+"."+i}". Its value is: "${f}"`);f[i]=typeof m=="function"?m(f[i],o):m,delete l[i]}return o},K=(t,e)=>j(t,e,!1),D=(t,e)=>j(t,e,!0);0&&(module.exports={isObjectLiteral,isStringIndex,modifyImmutably,parseStringIndex,remove,select,set,splitPathAtLastKey,updateImmutably});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var b=(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 P=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 K=t=>()=>t;var x=(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,d]of Object.entries(e)){if(!y)continue;let a=y.split("."),n=a.pop(),u=p,c=r;for(let h=0;h<a.length;h++){let s=a[h],i=c[s],m=typeof i=="object"&&(i.constructor===Object||Array.isArray(i)),f=o&&i===void 0;if(!m&&!f)throw new Error(`Invalid path provided: "${s}" is not an object/array in "${y}"`);u[s]||(f?c[s]=isNaN(a[h+1]??n)?{}:[]:c[s]=Array.isArray(i)?[...i]:{...i},u[s]={}),c=c[s],u=u[s]}let l=c;if(!o){if(Array.isArray(l)&&!(n<l.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(!l.hasOwnProperty(n))throw new Error(`Property ${n} doesnt exist in the path ${a.join(".")} because its value is ${l}`)}l[n]=typeof d=="function"?d(l[n],r):d,delete u[n]}return r};export{b as remove,T as select,K as set,P as splitPathAtLastKey,x as updateImmutably};
1
+ 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 i=Symbol(),p=[...t];return r.forEach(n=>{p[n]=i}),p.filter(n=>n!==i)}let o={...t};return r.forEach(i=>delete o[i]),o};var O=(t,e)=>!e||typeof e!="string"?t:e.split(".").reduce((r,o)=>{if(r?.hasOwnProperty(o))return r[o]},t);var g=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 A=t=>()=>t;var f=t=>!!t&&Object.getPrototypeOf(t)===Object.prototype;var j=t=>{let e=parseInt(t);return e.toString()===t?e:null},h=t=>parseInt(t).toString()===t;var x="${number}",I=(t,e,r)=>{if(!f(t)&&!Array.isArray(t))throw new Error(`"${t}" is not an literalObject/array`);if(!e)return t;let o=Array.isArray(t)?[...t]:{...t},i={};for(let[p,d]of Object.entries(e)){if(!p)continue;let n=p.split(".");if(n.includes(x))throw new Error(`"${x}" inside "${p}"`);let s=n.pop(),l=i,y=o;for(let u=0;u<n.length;u++){let a=n[u],c=y[a],T=f(c)||Array.isArray(c),b=r&&c===void 0;if(!T&&!b)throw new Error(`"${a}" doesnt exist in "${n.slice(0,u+1).join(".")}"`);l[a]||(b?y[a]=h(n[u+1]??s)?[]:{}:y[a]=Array.isArray(c)?[...c]:{...c},l[a]={}),y=y[a],l=l[a]}let m=y;if(!r&&!m.hasOwnProperty(s))throw new Error(`Property/Index "${s}" doesnt exist in the path "${n.join(".")+"."+s}". Its value is: "${m}"`);m[s]=typeof d=="function"?d(m[s],o):d,delete l[s]}return o},K=(t,e)=>I(t,e,!1),D=(t,e)=>I(t,e,!0);export{f as isObjectLiteral,h as isStringIndex,D as modifyImmutably,j as parseStringIndex,P as remove,O as select,A as set,g as splitPathAtLastKey,K as updateImmutably};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "maraj",
3
- "version": "2.4.1",
4
- "description": "A lightweight 500 bytes gzipped alternative for immutable updates while dealing with objects and arrays",
3
+ "version": "2.5.1",
4
+ "description": "A lightweight 600 bytes gzipped alternative for immutable updates while dealing with objects and arrays",
5
5
  "keywords": [
6
6
  "shallow",
7
7
  "shallow copy",
@@ -23,6 +23,7 @@
23
23
  "test": "vitest run",
24
24
  "build": "tsup src/index.ts --minify --format cjs,esm --dts",
25
25
  "lint": "tsc",
26
+ "trace": "tsc --generateTrace trace",
26
27
  "ci": "npm run lint && npm run test && npm run build",
27
28
  "release": "npm run lint && npm run test && npm run build && changeset publish"
28
29
  },
@@ -37,6 +38,7 @@
37
38
  "devDependencies": {
38
39
  "@changesets/cli": "^2.27.1",
39
40
  "@microsoft/api-extractor": "^7.38.5",
41
+ "@typescript/analyze-trace": "^0.10.1",
40
42
  "tsup": "^8.0.1",
41
43
  "typescript": "^5.3.3",
42
44
  "vitest": "^0.28.4"