Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript memo mode


May 09, 2021 CoffeeScript


Table of contents


Memo mode

Problem

You want to predict the reaction to an object after making a change.

Solution

Use Memo Pattern to track changes in an object. Classes that use this pattern output a memo object stored elsewhere.

If your application lets users edit text files, for example, they might want to undo the last action. You can save the existing state of the file before the user changes it, and then roll back to the previous location.

class PreserveableText
    class Memento
        constructor: (@text) ->

    constructor: (@text) ->
    save: (newText) ->
        memento = new Memento @text
        @text = newText
        memento
    restore: (memento) ->
        @text = memento.text

pt = new PreserveableText "The original string"
pt.text # => "The original string"

memento = pt.save "A new string"
pt.text # => "A new string"

pt.save "Yet another string"
pt.text # => "Yet another string"

pt.restore memento
pt.text # => "The original string"

Discuss

The memo object is returned by PreserveableText#save, which stores important status information separately for security reasons. You can serialize memos to ensure that data-intensive objects such as "undo" buffers on your hard drive or those edited images are available.