Hacker News new | ask | show | jobs
by andrewmackrodt 1161 days ago
They were serialising the previous object as a string (which may also contain a key called previous which is a string) so quoted values, backslashes and any other escape characters would be escaped. Over multiple screens this grows quickly, e.g. this simple struct which has only an id column grows to 2KB in only 9 steps:

    let obj = { id: 1 }

    for (let id = 2; id <= 10; id++) {
      obj = { id, previous: JSON.stringify(obj) }
    }
2 comments

The problem as stated is more complicated than it needs to be, due to forcing the serialized structure to match the in memory structure. Their in memory structure is a singly linked list. With JSON as a serialization format, that’s probably better modeled as an array with the “previous” link stored as the head (history[0]), and its “previous” stored as the tail (history[1]).

If this sounds like a cons cell, that’s what it is! It’s also a linked list. The laziness they want to achieve (only de/serialize one screen at a time per navigation forward or back) is also straightforward.

- forward: serialize the current screen, trim the leading/trailing quote off the previous serialization, insert with a comma before the new trailing bracket

- back: parse history, head is your desired “previous” screen, tail is your now-“previous” screen’s history

There’s a tiny amount of overhead to this approach, but not nearly as much as repeatedly reserializing the same string to shoehorn it into a serialized structure that doesn’t let you cheat a little bit with well known start/end characters.

Right, I was suggesting something like this (since we're already in JSON land, why leave it for string land):

    let obj = { id: 1 }

    for (let id = 2; id <= 10; id++) {
      obj = { id, previous: obj }
    }