CoursesAIMathCodePhysicsAbout and FAQ

TwiddleLab / Code / Data Structures You Can See

Undo Button and Leaderboard

Lesson 10 of 10 · 7 min · Free, no account needed

What you will learn

  • Undo and Redo run on two stacks: Undo moves the newest action from done to undone, Redo moves it back.
  • A new action empties the undone stack, or Redo would bring back a different history.
  • A top 3 only needs a few comparisons per new score: keep it sorted and let the 4th fall off.
  • A chatbot's memory window is a queue of fixed length: the oldest message leaves first.

Start the lesson

How the lesson goes

  1. Build the two features every app has: Undo, and a Top 3.

    Start with a tiny paint app. Draw something with 5 strokes.

  2. Redo needs a second stack.

    Undo puts strokes aside on undone; Redo takes them back. Do all three tasks.

    Both stacks hand back their newest item. Undo needs the newest stroke you did; Redo needs the newest stroke you undid. After a new stroke, the undone strokes belong to an old version of the drawing, so they're thrown away.

  3. The plan: two stacks.

    done is a stack of everything you did. undone is a stack of what you took back.

    undo(): pop from done, push onto undone. redo(): pop from undone, push onto done.

    Any new action is pushed onto done, and undone is emptied.

  4. Write undo().

    Two undos should leave red on done, and green then blue on undone.

  5. Someone else's Redo has a bug.

    Watch the demo, then pick the fix.

  6. Your code, behind your drawing's Undo button.

    Each press runs your undo() for real.

  7. Now the leaderboard: a live top 3.

    Scores arrive one at a time. Put each one in its place, or out.

  8. Top 3 live.

    Twelve scores, fast. Tap where each goes.

  9. A chatbot's memory is a queue too.

    This bot can only keep 4 messages. When a new one comes in, which does it forget?

  10. Your project card.

    Your drawing, your Undo, your leaderboard.

Previous lesson: Choosing the Right Structure · Part of the course: Data Structures You Can See

Lessons are interactive and need JavaScript. Turn it on to play them.

Loading TwiddleLab