Deep-clone a station graph, skipping closed stations
A trip planner keeps the rail network as a graph of station objects. Before it simulates a weekend closure, it needs a private copy of the network with the closed stations taken out, so the live map is never touched.
Implement cloneNetwork(start, isClosed?). It returns a deep copy of every open station reachable from start, and returns the copy of start.
cloneNetwork(start, isClosed?) // => copy of start, or null
{ name, links }. name is a string and links is an array of stations.B is in A.links, then A is in B.links. A station may link to itself (it then appears once in its own links). A link never appears twice in the same array.{ name, links } with a new links array. No object or array in the result comes from the input.C, their copies link to the same copy of C. Cycles in the network become cycles in the copy.links keep the original order, minus any closed stations.isClosed(station) is optional and receives an original station. When it returns a truthy value, that station is not copied and every link to it is dropped. Stations you can only reach through closed stations are not copied either. Without isClosed, every station is open.isClosed at most once per station.null when start is null or undefined, or when start itself is closed.// Harbor -- Market -- Museum
// \ /
// ----- Airport ----
const harbor = { name: 'Harbor', links: [] };
const market = { name: 'Market', links: [] };
const museum = { name: 'Museum', links: [] };
const airport = { name: 'Airport', links: [] };
harbor.links.push(market, airport);
market.links.push(harbor, museum);
museum.links.push(market, airport);
airport.links.push(harbor, museum);
const copy = cloneNetwork(harbor);
copy === harbor; // => false
copy.links.map((s) => s.name); // => ['Market', 'Airport']
copy.links[0].links[1] === copy.links[1].links[1]; // => true (one Museum copy)
copy.links[0].links[0] === copy; // => true (the cycle is kept)
const weekend = cloneNetwork(harbor, (s) => s.name === 'Airport');
weekend.links.map((s) => s.name); // => ['Market']
weekend.links[0].links[1].links.map((s) => s.name); // => ['Market'] (Museum lost its Airport link)
cloneNetwork(harbor, (s) => s.name === 'Harbor'); // => null
cloneNetwork(null); // => null