Fixed bug, wrote readme
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 2b2d0cb · Browse files · 4 files·+236 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+236 added−15 removed
- tests:+90 added−11 removed
- other:+146 added−4 removed
Provenance
- Commit
1b8a694- Tree
da02aff- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
2b2d0cb
4 files changed+236 added−15 removed
modified:__tests__/base.js+90 added-11 removed
123 unmodified linesExpand all124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176132177134135136137138139140141142178179180181182183184185186187188189145190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224123 unmodified linesExpand all expect(nextState.anArray).not.toBe(baseState.anArray) expect(nextState.anArray).toEqual([3, 2, { c: 3, test: true }, 1]) })
it("reusing object should work", () => { const nextState = immer(baseState, s => { debugger const obj = s.anObject delete s.anObject s.messy = obj }) expect(nextState).not.toBe(baseState) expect(nextState.anArray).toBe(baseState.anArray) expect(nextState).toEqual({ anArray: [3, 2, { c: 3 }, 1], aProp: "hi", messy: { nested: { yummie: true }, coffee: false } }) expect(nextState.messy.nested).toBe(baseState.anObject.nested) })
it("refs should be transparent", () => { const nextState = immer(baseState, s => { const obj = s.anObject s.aProp = "hello" delete s.anObject obj.coffee = true s.messy = obj }) expect(nextState).not.toBe(baseState) expect(nextState.anArray).toBe(baseState.anArray) expect(nextState).toEqual({ anArray: [3, 2, { c: 3 }, 1], aProp: "hello", messy: { nested: { yummie: true }, coffee: true } }) expect(nextState.messy.nested).toBe(baseState.anObject.nested) })
afterEach(() => { expect(baseState).toBe(origBaseState) expect(baseState).toEqual(createBaseState()) })})
function createBaseState() { return { anArray: [3, 2, { c: 3 }, 1], aProp: "hi", anObject: { nested: { yummie: true }, coffee: false function createBaseState() { return { anArray: [3, 2, { c: 3 }, 1], aProp: "hi", anObject: { nested: { yummie: true }, coffee: false } } }}})
describe("readme example", () => { it("works", () => { const baseState = [ { todo: "Learn typescript", done: true }, { todo: "Try immer", done: false } ]
const nextState = immer(baseState, state => { state.push({ todo: "Tweet about it" }) state[1].done = true })
// the new item is only added to the next state, // base state is unmodified expect(baseState.length).toBe(2) expect(nextState.length).toBe(3)
// same for the changed 'done' prop expect(baseState[1].done).toBe(false) expect(nextState[1].done).toBe(true)
// unchanged data is structurally shared expect(nextState[0]).toBe(baseState[0]) // changed data not (dûh) expect(nextState[1]).not.toBe(baseState[1]) })})modified:immer.js+11 added-2 removed
1 // @ts-check2 3+const isProxySymbol = Symbol("immer-proxy")4+5 /**6 * Immer takes a state, and runs a function agains it.7 * That function can freely mutate the state, as it will create copies-on-write.8 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned10 unmodified lines19 const copies = new Map()20 21 const objectTraps = {22 get(target, prop) {23+ if (prop === isProxySymbol) return target24 return createProxy(getCurrentSource(target)[prop])25 },26 has(target, prop) {27 return prop in getCurrentSource(target)5 unmodified lines33 const current = createProxy(getCurrentSource(target)[prop])34 const newValue = createProxy(value)35 if (current !== newValue) {36 const copy = getOrCreateCopy(target)34- copy[prop] = newValue37+ copy[prop] = isProxy(newValue) ? newValue[isProxySymbol] : newValue38 }39 return true40 },41 deleteProperty(target, property) {21 unmodified lines63 64 // creates a proxy for plain objects / arrays65 function createProxy(base) {66 if (isPlainObject(base) || Array.isArray(base)) {67+ if (isProxy(base)) return base // avoid double wrapping68 if (proxies.has(base)) return proxies.get(base)69 const proxy = new Proxy(base, objectTraps)70 proxies.set(base, proxy)71 return proxy9 unmodified lines81 if (copies.has(base)) return true // a copy was created, so there are changes82 // look deeper83 const keys = Object.keys(base)84 for (let i = 0; i < keys.length; i++) {81- if (hasChanges(base[keys[i]])) return true85+ const value = base[keys[i]]86+ if ((Array.isArray(value) || isPlainObject(value)) && hasChanges(value)) return true87 }88 return false89 }90 35 unmodified lines126 const proto = Object.getPrototypeOf(value)127 return proto === Object.prototype || proto === null128 }129 130+function isProxy(value) {131+ return !!value[isProxySymbol]132+}133+134 module.exports = immermodified:package.json+4 added-1 removed
1 {2 "name": "immer",3- "version": "0.0.1",3+ "version": "0.0.2",4 "description": "Create your next immutable state by mutating the current one",5 "main": "immer.js",6 "scripts": {7 "test": "jest"12 unmodified lines20 "bugs": {21 "url": "https://github.com/mweststrate/immer/issues"22 },23 "homepage": "https://github.com/mweststrate/immer#readme",24+ "files": [25+ "immer.js"26+ ],27 "dependencies": {},28 "devDependencies": {29 "@types/jest": "^22.0.0",30 "babel-core": "^6.26.0",12 unmodified linesmodified:readme.md+131 added-1 removed
1-Soon!1+# Immer2+3+Immer (German for: always) is a tiny package that allows you work with immutable state in a more convenient way.4+It is based on [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.5+6+The basic idea is that you will modify (a proxy of) the current state, and once that is completed, the copy will be finalized and form the next state.7+As soon as a piece of the state is modified, it is copied. That is what one typically does by hand (in for example Redux reducers).8+9+_This means that you can interact with your data by using mutations, will keeping all the benefits of immutable data_10+11+The immer package exposes a single function:12+13+`immer(currentState, fn: (state) => void): nextState`14+15+## Example16+17+```javascript18+const baseState = [19+ {20+ todo: "Learn typescript",21+ done: true22+ },23+ {24+ todo: "Try immer",25+ done: false26+ }27+]28+29+const nextState = immer(baseState, state => {30+ state.push({ todo: "Tweet about it" })31+ state[1].done = true32+})33+```34+35+The interesting thing about `immer` is that `baseState` will be untouched, but that `nextState` will reflect all changes made to `state`.36+37+```javascript38+// the new item is only added to the next state,39+// base state is unmodified40+expect(baseState.length).toBe(2)41+expect(nextState.length).toBe(3)42+43+// same for the changed 'done' prop44+expect(baseState[1].done).toBe(false)45+expect(nextState[1].done).toBe(true)46+47+// unchanged data is structurally shared48+expect(nextState[0]).toBe(baseState[0])49+// changed data not (dûh)50+expect(nextState[1]).not.toBe(baseState[1])51+```52+53+## Reducer Example54+55+A lot of words; here is a simple example of what difference that could make in practice.56+The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)57+58+```javascript59+const todo = (state, action) => {60+ switch (action.type) {61+ case 'ADD_TODO':62+ return {63+ id: action.id,64+ text: action.text,65+ completed: false66+ }67+ case 'TOGGLE_TODO':68+ if (state.id !== action.id) {69+ return state70+ }71+72+ return {73+ ...state,74+ completed: !state.completed75+ }76+ default:77+ return state78+ }79+}80+81+const todos = (state = [], action) => {82+ switch (action.type) {83+ case 'ADD_TODO':84+ return [85+ ...state,86+ todo(undefined, action)87+ ]88+ case 'TOGGLE_TODO':89+ return state.map(t =>90+ todo(t, action)91+ )92+ default:93+ return state94+ }95+}96+```97+98+After using immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):99+100+```javascript101+import immer from 'immer'102+103+const todos = (state = [], action) =>104+ immer(state, state => {105+ switch (action.type) {106+ case 'ADD_TODO':107+ state.push({108+ id: action.id,109+ text: action.text,110+ completed: false111+ })112+ return113+ case 'TOGGLE_TODO':114+ const todo = state.find(todo => todo.id === action.id)115+ todo.completed = !todo.completed116+ return117+ }118+ })119+```120+121+Creating middleware or reducer wrapper that applies `immer` automatically is left as exercise to the reader :-).122+123+## Limitations124+125+* This package requires Proxies, so Safari > 10, no Internet Explorer126+* Currently only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)127+* Currently only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)128+129+## Pitfalls:130+131+* 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`!