Serialize a Key-Value Store
Implement serialization for an in-memory key-value store whose keys and values are strings.
serialize(store)takes a plain object and returns a single string that could be written to a file or sent over a network.deserialize(text)takes that string and returns an object equal to the original.
Keys and values may be empty and may contain any character: spaces, newlines, quotes, digits, and whatever separator you might pick. The format is yours to design, and designing it is the exercise, so do not hand the work to JSON.stringify or another built-in encoder.
store = { "user:1": "alice", "note": "a=b;c\nd", "empty": "" }
deserialize(serialize(store)) // deep-equals storeThe tests round-trip a store through your two functions; the order of keys does not matter. Only the task itself was given in the interview, so be ready to justify the format and to say what you would ask about value types and size.
Hints
Hint 1
A format like key=value;key=value breaks as soon as a key or value contains = or ;. Escaping fixes that, but there is a simpler idea.
Hint 2
Tell the reader how long the next field is before it starts: <length>:<characters>. The reader then takes exactly that many characters without looking at them.
Hint 3
List the inputs most likely to break a round trip, such as empty strings, a value that looks like your own header (3:abc), and newlines, and check the format against each before coding.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.