maraj 1.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.
Files changed (2) hide show
  1. package/index.js +49 -0
  2. package/package.json +11 -0
package/index.js ADDED
@@ -0,0 +1,49 @@
1
+ //creates
2
+ const createImmutableUpdate = (state, update = {}) => {
3
+ const newState = Array.isArray(state) ? [...state] : { ...state }
4
+ const visited = {}
5
+ for (const [path, value] of Object.entries(update)) {
6
+ if (!path || path === 'false' || path === 'undefined' || path === 'null') continue
7
+ let keys = path.split(".")
8
+ let lastkey = keys.pop()
9
+ let tracker = visited
10
+ let current = newState
11
+ for (let key of keys) {
12
+ if (typeof current[key] !== 'object') throw new Error(`Destructure "${key}" in "${path}" with value: ${current[key]}`)
13
+ if (!tracker[key]) {
14
+ current[key] = Array.isArray(current[key]) ? [...current[key]] : { ...current[key] }
15
+ tracker[key] = {}
16
+ }
17
+ current = current[key]
18
+ tracker = tracker[key]
19
+ }
20
+ delete tracker[lastkey]
21
+ current[lastkey] = typeof value === 'function' ? value(current[lastkey]) : value
22
+ }
23
+ return newState
24
+ }
25
+ export default createImmutableUpdate
26
+
27
+ export const createSelectorFromStringPath = (path) => (state) => path.split(".").reduce((current, key) => current[key], state)
28
+
29
+ // spread object or array, if its not object or array it just assigns its value
30
+ export const spread = (update) => (value) => {
31
+ if (value?.constructor === Object && update?.constructor === Object) return { ...value, ...update }
32
+ if (Array.isArray(value) && Array.isArray(update)) return [...value, ...update]
33
+ return update
34
+ }
35
+
36
+ // a string/number/array of index or properties(key)
37
+ export const remove = (keys) => (value) => {
38
+ if (typeof value !== 'object') return value
39
+ if (typeof keys !== 'object') keys = [keys]
40
+ if (Array.isArray(value)) return value.filter((v, i) => (!keys.includes(i) || (keys.splice(keys.indexOf(i), 1) && false)))
41
+ const update = { ...value }
42
+ keys.forEach(key => delete update[key])
43
+ return update
44
+ }
45
+ // splits a string id path
46
+ export const splitPath = (path) => ({
47
+ remainingPath: path.slice(0, path.lastIndexOf(".") + 1),
48
+ id: path.slice(path.lastIndexOf(".") + 1),
49
+ })
package/package.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "maraj",
3
+ "version": "1.0.0",
4
+ "description": "A lightweight 500 bytes alternative for immutable updates while dealing with objects and arrays",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "author": "Lukasz Maraj",
10
+ "license": "ISC"
11
+ }