forked from immerjs/immer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurry.js
100 lines (86 loc) · 2.32 KB
/
curry.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"use strict"
import {
produce,
setUseProxies,
produceWithPatches,
enablePatches
} from "../src/immer"
enablePatches()
runTests("proxy", true)
function runTests(name) {
describe("curry - " + name, () => {
it("should check arguments", () => {
expect(() => produce()).toThrowErrorMatchingSnapshot()
expect(() => produce({})).toThrowErrorMatchingSnapshot()
expect(() => produce({}, {})).toThrowErrorMatchingSnapshot()
expect(() => produce({}, () => {}, [])).toThrowErrorMatchingSnapshot()
})
it("should support currying", () => {
const state = [{}, {}, {}]
const mapper = produce((item, index) => {
item.index = index
})
expect(state.map(mapper)).not.toBe(state)
expect(state.map(mapper)).toEqual([{index: 0}, {index: 1}, {index: 2}])
expect(state).toEqual([{}, {}, {}])
})
it("should support returning new states from curring", () => {
const reducer = produce((item, index) => {
if (!item) {
return {hello: "world"}
}
item.index = index
})
expect(reducer(undefined, 3)).toEqual({hello: "world"})
expect(reducer({}, 3)).toEqual({index: 3})
})
it("should support passing an initial state as second argument", () => {
const reducer = produce(
(item, index) => {
item.index = index
},
{hello: "world"}
)
expect(reducer(undefined, 3)).toEqual({hello: "world", index: 3})
expect(reducer({}, 3)).toEqual({index: 3})
expect(reducer()).toEqual({hello: "world", index: undefined})
})
it("can has fun with change detection", () => {
const spread = produce(Object.assign)
const base = {
x: 1,
y: 1
}
expect({...base}).not.toBe(base)
expect(spread(base, {})).toBe(base)
expect(spread(base, {y: 1})).toBe(base)
expect(spread(base, {...base})).toBe(base)
expect(spread(base, {...base, y: 2})).not.toBe(base)
expect(spread(base, {...base, y: 2})).toEqual({x: 1, y: 2})
expect(spread(base, {z: 3})).toEqual({x: 1, y: 1, z: 3})
expect(spread(base, {y: 1})).toBe(base)
})
})
it("support currying for produceWithPatches", () => {
const increment = produceWithPatches((draft, delta) => {
draft.x += delta
})
expect(increment({x: 5}, 2)).toEqual([
{x: 7},
[
{
op: "replace",
path: ["x"],
value: 7
}
],
[
{
op: "replace",
path: ["x"],
value: 5
}
]
])
})
}