Created
May 23, 2021 18:01
-
-
Save iskenxan/cad36ee343569f728ad56f9fa9d81626 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import produce, { applyPatches, enablePatches } from "immer"; | |
enablePatches(); | |
export const RESET = "RESET"; | |
export const OPEN_DOOR = "OPEN_DOOR"; | |
export const UNDO = "UNDO"; | |
let inverseChanges = []; | |
export const reducer = (state, action) => { | |
return produce( | |
state, | |
(draft) => { | |
switch (action.type) { | |
case OPEN_DOOR: { | |
const { index } = action.payload; | |
draft.doors[index].isOpen = true; | |
break; | |
} | |
case RESET: { | |
draft.doors = generateDoors(); | |
inverseChanges = []; | |
break; | |
} | |
case UNDO: { | |
if (inverseChanges.length > 0) { | |
return applyPatches(state, [inverseChanges.pop()]); | |
} | |
break; | |
} | |
default: | |
break; | |
} | |
}, | |
(patches, inversePatches) => { | |
if (action.type === OPEN_DOOR) { | |
inverseChanges.push(...inversePatches); | |
} | |
} | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment