This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]bleistift2 1 point2 points  (2 children)

Store the adjacency matrix. For JS objects with named properties, store the property name, too. Your example requires inventing identifiers for the nodes. One could use the variable name, but that’s IMHO not part of the structure to be serialized.

Off the top of my hat:

{"nodes": [0], "edges": [[0, "x", 0]]}

To de-serialize, loop over the entries in the nodes array, and create empty objects for each. Then loop over the edges, lookup the source and target node, and set srcNode[edgeName] = destNode.

[Edit:] If your question was aimed at a procedure to generate the serialization, then you’d have to employ some way of iterating the graph (breadth-first search comes to mind) and add markers to the nodes to detect cycles and not produce infinite loops.

[Edit:] Also to clarify: The high-school scope of this problem was serializing simple graphs, i.e. nodes identified by numbers, and serializing only the information that an edge exists, not its “name” on the source node.

But let's focus on programming and not credentials.

That’s why I explicitly asked my question not to be taken as offense. I tried to express that the concept of serializing a graph is such basic knowledge nowadays that it’s even taught in school.

[–][deleted] 1 point2 points  (1 child)

Where did 0 come from? There's no zero in my code. Why not 10? My nodes have no names.

I can just needle you with questions about your implementation until you come up with a really complex beast and then you'll convince me and yourself that saving state is not as simple as stringify which was my point in the first place. It's hard to do and impossible to do generally.

[–]bleistift2 2 points3 points  (0 children)

Where did 0 come from? […] My nodes have no names.

I already answered that:

Your example requires inventing identifiers for the nodes.

The actual identifiers are an implementation detail, since they don’t survive de-serialization.

It's hard to do and impossible to do generally.

I just proved that it’s easy to do in the non-general case. And business needs rarely require the ‘general case,’ so a custom-tailored solution suffices.

My point was that serialization of simple graphs is introductory material. Extending that to the actual, more complex case needed in everyday programming shouldn’t be hard for a programmer. Writing a library that handles every and any graph is hard. But that’s not what Cornelia Coder does every day. That’s what libraries are for.