Merge branch 'master' into issue10
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by GitHub · parents 5475b84, a151fed · Browse files · 7 files·+129 added−42 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+129 added−42 removed
- tests:+32 added−22 removed
- other:+97 added−20 removed
Provenance
- Commit
d928d11- Tree
17dc315- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
5475b84- Parent 2
a151fed
7 files changed+129 added−42 removed
modified:__tests__/base.js+32 added-22 removed
14 unmodified lines15 16 it("should return the original without modifications when reading stuff", () => {17 const nextState = immer(baseState, s => {18 expect(s.aProp).toBe("hi")19- expect(s.anObject.nested).toEqual({ yummie: true })19+ expect(s.anObject.nested).toEqual({yummie: true})20 })21 expect(nextState).toBe(baseState)22 })23 24+ it("should not return any value: thunk", () => {25+ const warning = jest.spyOn(console, "warn")26+ immer(baseState, () => ({bad: "don't do this"}))27+ immer(baseState, () => [1, 2, 3])28+ immer(baseState, () => false)29+ immer(baseState, () => "")30+31+ expect(warning).toHaveBeenCalledTimes(4)32+ })33+34 it("should return a copy when modifying stuff", () => {35 const nextState = immer(baseState, s => {36 s.aProp = "hello world"37 })16 unmodified lines54 })55 56 it("can add props", () => {57 const nextState = immer(baseState, s => {48- s.anObject.cookie = { tasty: true }58+ s.anObject.cookie = {tasty: true}59 })60 expect(nextState).not.toBe(baseState)61 expect(nextState.anObject).not.toBe(baseState.anObject)62 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)53- expect(nextState.anObject.cookie).toEqual({ tasty: true })63+ expect(nextState.anObject.cookie).toEqual({tasty: true})64 })65 66 it("can delete props", () => {67 const nextState = immer(baseState, s => {43 unmodified lines111 })112 expect(nextState).not.toBe(baseState)113 expect(nextState.anArray).not.toBe(baseState.anArray)114 105- expect(nextState.anArray).toEqual([3, "a", "b", { c: 3 }, 1])115+ expect(nextState.anArray).toEqual([3, "a", "b", {c: 3}, 1])116 })117 118 it("should support sorting arrays", () => {119 const nextState = immer(baseState, s => {2 unmodified lines122 s.anArray[3].c = 5123 })124 expect(nextState).not.toBe(baseState)125 expect(nextState.anArray).not.toBe(baseState.anArray)116- expect(nextState.anArray).toEqual([1, 2, 3, { c: 5 }])126+ expect(nextState.anArray).toEqual([1, 2, 3, {c: 5}])127 })128 129 it("should updating inside arrays", () => {130 const nextState = immer(baseState, s => {131 s.anArray[2].test = true132 })133 expect(nextState).not.toBe(baseState)134 expect(nextState.anArray).not.toBe(baseState.anArray)125- expect(nextState.anArray).toEqual([3, 2, { c: 3, test: true }, 1])135+ expect(nextState.anArray).toEqual([3, 2, {c: 3, test: true}, 1])136 })137 138 it("reusing object should work", () => {139 const nextState = immer(baseState, s => {4 unmodified lines144 })145 expect(nextState).not.toBe(baseState)146 expect(nextState.anArray).toBe(baseState.anArray)147 expect(nextState).toEqual({138- anArray: [3, 2, { c: 3 }, 1],148+ anArray: [3, 2, {c: 3}, 1],149 aProp: "hi",150 messy: {151 nested: {142- yummie: true152+ yummie: true,153 },144- coffee: false145- }154+ coffee: false,155+ },156 })157 expect(nextState.messy.nested).toBe(baseState.anObject.nested)158 })159 7 unmodified lines167 })168 expect(nextState).not.toBe(baseState)169 expect(nextState.anArray).toBe(baseState.anArray)170 expect(nextState).toEqual({161- anArray: [3, 2, { c: 3 }, 1],171+ anArray: [3, 2, {c: 3}, 1],172 aProp: "hello",173 messy: {174 nested: {165- yummie: true175+ yummie: true,176 },167- coffee: true168- }177+ coffee: true,178+ },179 })180 expect(nextState.messy.nested).toBe(baseState.anObject.nested)181 })182 35 unmodified lines218 })219 220 function createBaseState() {221 return {212- anArray: [3, 2, { c: 3 }, 1],222+ anArray: [3, 2, {c: 3}, 1],223 aProp: "hi",224 anObject: {225 nested: {216- yummie: true226+ yummie: true,227 },218- coffee: false219- }228+ coffee: false,229+ },230 }231 }232 })233 1 unmodified line235 it("works", () => {236 const baseState = [237 {238 todo: "Learn typescript",229- done: true239+ done: true,240 },241 {242 todo: "Try immer",233- done: false234- }243+ done: false,244+ },245 ]246 247 const nextState = immer(baseState, state => {238- state.push({ todo: "Tweet about it" })248+ state.push({todo: "Tweet about it"})249 state[1].done = true250 })251 252 // the new item is only added to the next state,14 unmodified linesmodified:.gitignore+1 added
55 unmodified lines56 57 # dotenv environment variables file58 .env59 60+.ideaadded:.prettierrc+19 added
1+{2+ "bracketSpacing": false,3+ "printWidth": 80,4+ "proseWrap": "never",5+ "requirePragma": false,6+ "semi": false,7+ "singleQuote": false,8+ "tabWidth": 4,9+ "trailingComma": "all",10+ "useTabs": false,11+ "overrides": [12+ {13+ "files": "*.json",14+ "options": {15+ "printWidth": 20016+ }17+ }18+ ]19+}modified:immer.js+15 added-4 removed
43 unmodified lines44454647484849505152535455565756585960616233 unmodified lines969798999810010110210310410510610710824 unmodified lines13313413513613113713813914014114214314414514624 unmodified lines43 unmodified lines const current = createProxy(getCurrentSource(target)[prop]) const newValue = createProxy(value) if (current !== newValue) { const copy = getOrCreateCopy(target) copy[prop] = isProxy(newValue) ? newValue[isProxySymbol] : newValue copy[prop] = isProxy(newValue) ? newValue[isProxySymbol] : newValue } return true }, deleteProperty(target, property) { const copy = getOrCreateCopy(target) delete copy[property] return true } }, }
// creates a copy for a base object if there ain't one function getOrCreateCopy(base) {33 unmodified lines // look deeper const keys = Object.keys(base) for (let i = 0; i < keys.length; i++) { const value = base[keys[i]] if ((Array.isArray(value) || isPlainObject(value)) && hasChanges(value)) return true if ( (Array.isArray(value) || isPlainObject(value)) && hasChanges(value) ) return true } return false }
24 unmodified lines
// create proxy for root const rootClone = createProxy(baseState) // execute the thunk thunk(rootClone) const maybeVoidReturn = thunk(rootClone) //values either than undefined will trigger warning; !Object.is(maybeVoidReturn, undefined) && console.warn( `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`, ) // revoke all proxies revoke(revocableProxies) // and finalize the modified proxy return finalize(baseState)24 unmodified linesmodified:package.json+7 added-2 removed
3 unmodified lines4 "description": "Create your next immutable state by mutating the current one",5 "main": "immer.js",6 "types": "./index.d.ts",7 "scripts": {8- "test": "jest"8+ "test": "jest",9+ "prettier": "prettier \"*/**/*.js\" --ignore-path ./.prettierignore --write && git add . && git status"10 },11+ "pre-commit": [12+ "prettier"13+ ],14 "repository": {15 "type": "git",16 "url": "git+https://github.com/mweststrate/immer.git"17 },10 unmodified lines28 "homepage": "https://github.com/mweststrate/immer#readme",29 "files": [30 "immer.js"31 ],28- "dependencies": {},32 "devDependencies": {33 "@types/jest": "^22.0.0",34 "babel-core": "^6.26.0",35 "babel-jest": "^22.0.4",36 "babel-preset-env": "^1.6.1",37 "jest": "^22.0.4",38+ "pre-commit": "^1.2.2",39+ "prettier": "^1.9.2",40 "regenerator-runtime": "^0.11.1",41 "typescript": "^2.6.2"42 },43 "jest": {5 unmodified linesmodified:readme.md+12 added-12 removed
1 # Immer2 3-_Your personally assistance for creating your next immutable state_3+_Your personal assistant for creating your next immutable state_4 5 ---6 7 Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.8 It is based on [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.9 10-The basic idea is that you will apply all your changes to a _draftState_. Which is a proxy of the _currentState_, and once all your mutations are completed, immer will produce the _nextState_ based on the mutations to the draft state. This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.10+The basic idea is that, you will apply all your changes to a _draftState_, which is a proxy of the _currentState_ and once all your mutations are completed, immer will produce the _nextState_ based on the mutations to the draft state. This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.11 12 <center>13 14 15 16-Using immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jod changes onto. Once you are done the assistant will take your draft and produce the real immutable, final letter for you (the next state).16+Using immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).17 </center>18 19 ## API20 20 unmodified lines41 draftState[1].done = true42 })43 ```44 45-The interesting thing about `immer` is that `baseState` will be untouched, but that `nextState` will reflect all changes made to `draftState`.45+The interesting thing about `immer` is that, the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.46 47 ```javascript48 // the new item is only added to the next state,49 // base state is unmodified19 unmodified lines69 * No accidental mutations of current state, but intentional mutations of a draft state70 71 ## Reducer Example72 73-A lot of words; here is a simple example of what difference that could make in practice.73+A lot of words; here is a simple example of the difference that this approach could make in practice.74 The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)75 76-_Note, this is just a sample application of the `immer` package. Immer is design to just simply Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_76+_Note, this is just a sample application of the `immer` package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_77 78 ```javascript79 const todo = (state, action) => {80 switch (action.type) {57 unmodified lines138 }139 })140 ```141 142-Creating middleware or reducer wrapper that applies `immer` automatically is left as exercise to the reader :-).142+Creating middleware or a reducer wrapper that applies `immer` automatically is left as exercise for the reader :-).143 144 ## Limitations145 146 * This package requires Proxies, so Safari > 10, no Internet Explorer147-* Currently only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)148-* Currently only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)147+* Currently, only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)148+* Currently, only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)149 150 ## Pitfalls:151 152-* Make sure to modify the state you get passed in in the callback function, not the original base state that was passed as first argument to `immer`!153-* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before optimize!), do the current state analysis before entering the `immer` block or read form the `currentState` rather than the `draftState`152+* Make sure to modify the draft state you get passed in in the callback function, not the original current state that was passed as the first argument to `immer`!153+* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the `immer` block or read from the `currentState` rather than the `draftState`154 155 ## Changelog156 157 ### 0.0.4 (31-12-2017)158 159 * Added typescript typings [#11](https://github.com/mweststrate/immer/pull/11) by [@benbraou](https://github.com/benbraou)160-* Fixed bug when setting properties to `undefined`. Fixes [#12](https://github.com/mweststrate/immer/issues/12) through [#13](https://github.com/mweststrate/immer/pull/13) by [@benbraou](https://github.com/benbraou)160+* Fixed bug when setting properties to `undefined`. Fixes [#12](https://github.com/mweststrate/immer/issues/12) through [#13](https://github.com/mweststrate/immer/pull/13) by [@benbraou](https://github.com/benbraou)modified:yarn.lock+43 added-2 removed
839 unmodified lines840 concat-map@0.0.1:841 version "0.0.1"842 resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"843 844+concat-stream@^1.4.7:845+ version "1.6.0"846+ resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.0.tgz#0aac662fd52be78964d5532f694784e70110acf7"847+ dependencies:848+ inherits "^2.0.3"849+ readable-stream "^2.2.2"850+ typedarray "^0.0.6"851+852 console-control-strings@^1.0.0, console-control-strings@~1.1.0:853 version "1.1.0"854 resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e"855 556 unmodified lines1412 dependencies:1413 once "^1.3.0"1414 wrappy "1"1415 1408-inherits@2, inherits@~2.0.0, inherits@~2.0.3:1416+inherits@2, inherits@^2.0.3, inherits@~2.0.0, inherits@~2.0.3:1417 version "2.0.3"1418 resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"1419 1420 ini@~1.3.0:838 unmodified lines2259 execa "^0.7.0"2260 lcid "^1.0.0"2261 mem "^1.1.0"2262 2263+os-shim@^0.1.2:2264+ version "0.1.3"2265+ resolved "https://registry.yarnpkg.com/os-shim/-/os-shim-0.1.3.tgz#6b62c3791cf7909ea35ed46e17658bb417cb3917"2266+2267 os-tmpdir@^1.0.0, os-tmpdir@^1.0.1:2268 version "1.0.2"2269 resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274"2270 94 unmodified lines2365 pn@^1.0.0:2366 version "1.0.0"2367 resolved "https://registry.yarnpkg.com/pn/-/pn-1.0.0.tgz#1cf5a30b0d806cd18f88fc41a6b5d4ad615b3ba9"2368 2369+pre-commit@^1.2.2:2370+ version "1.2.2"2371+ resolved "https://registry.yarnpkg.com/pre-commit/-/pre-commit-1.2.2.tgz#dbcee0ee9de7235e57f79c56d7ce94641a69eec6"2372+ dependencies:2373+ cross-spawn "^5.0.1"2374+ spawn-sync "^1.0.15"2375+ which "1.2.x"2376+2377 prelude-ls@~1.1.2:2378 version "1.1.2"2379 resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54"2380 2381 preserve@^0.2.0:2382 version "0.2.0"2383 resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b"2384 2385+prettier@^1.9.2:2386+ version "1.9.2"2387+ resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.9.2.tgz#96bc2132f7a32338e6078aeb29727178c6335827"2388+2389 pretty-format@^22.0.3:2390 version "22.0.3"2391 resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-22.0.3.tgz#a2bfa59fc33ad24aa4429981bb52524b41ba5dd7"2392 dependencies:58 unmodified lines2451 load-json-file "^1.0.0"2452 normalize-package-data "^2.3.2"2453 path-type "^1.0.0"2454 2431-readable-stream@^2.0.1, readable-stream@^2.0.6, readable-stream@^2.1.4:2455+readable-stream@^2.0.1, readable-stream@^2.0.6, readable-stream@^2.1.4, readable-stream@^2.2.2:2456 version "2.3.3"2457 resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.3.tgz#368f2512d79f9d46fdfc71349ae7878bbc1eb95c"2458 dependencies:2459 core-util-is "~1.0.0"249 unmodified lines2709 source-map@^0.6.0:2710 version "0.6.1"2711 resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"2712 2713+spawn-sync@^1.0.15:2714+ version "1.0.15"2715+ resolved "https://registry.yarnpkg.com/spawn-sync/-/spawn-sync-1.0.15.tgz#b00799557eb7fb0c8376c29d44e8a1ea67e57476"2716+ dependencies:2717+ concat-stream "^1.4.7"2718+ os-shim "^0.1.2"2719+2720 spdx-correct@~1.0.0:2721 version "1.0.2"2722 resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-1.0.2.tgz#4b3073d933ff51f3912f03ac5519498a4150db40"2723 dependencies:189 unmodified lines2913 resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72"2914 dependencies:2915 prelude-ls "~1.1.2"2916 2917+typedarray@^0.0.6:2918+ version "0.0.6"2919+ resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777"2920+2921 typescript@^2.6.2:2922 version "2.6.2"2923 resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.6.2.tgz#3c5b6fd7f6de0914269027f03c0946758f7673a4"2924 85 unmodified lines3010 which-module@^2.0.0:3011 version "2.0.0"3012 resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a"3013 3014+which@1.2.x:3015+ version "1.2.14"3016+ resolved "https://registry.yarnpkg.com/which/-/which-1.2.14.tgz#9a87c4378f03e827cecaf1acdf56c736c01c14e5"3017+ dependencies:3018+ isexe "^2.0.0"3019+3020 which@^1.2.12, which@^1.2.9:3021 version "1.3.0"3022 resolved "https://registry.yarnpkg.com/which/-/which-1.3.0.tgz#ff04bdfc010ee547d780bec38e1ac1c2777d253a"3023 dependencies:86 unmodified lines