charkour / zundo

🍜 undo/redo middleware for zustand. <700 bytes
https://codesandbox.io/s/zundo-2dom9
MIT License
616 stars 20 forks source link

Can this be re-written to avoid loops altogether and simply use an array method to splice the array at the specific index? #105

Closed charkour closed 1 year ago

charkour commented 1 year ago
     undo: (steps = 1) => {
        // Fastest way to clone an array on Chromium. Needed to create a new array reference
        const pastStates = get().pastStates.slice();
        const futureStates = get().futureStates.slice();
        if (pastStates.length) {
          // Based on the steps, get values from the pastStates array and push them to the futureStates array
          for (let i = 0; i < steps; i++) {
            const pastState = pastStates.pop();
            if (pastState) {
              futureStates.push(options?.partialize?.(userGet()) || userGet());
              userSet(pastState);
            }
          }
          set({ pastStates, futureStates });
        }
charkour commented 1 year ago

https://stackoverflow.com/questions/6872630/split-an-array-into-two-based-on-a-index-in-javascript

charkour commented 1 year ago

117