Add a copy method to `analysis/weights`

It's very simple: a method that creates a copy of a `Weights`.
While writing this, I realized I should probably refactor the weights
module so that it exports a class rather than a bunch of methods
operating on a data structure. It would just be a cleaner API. But I'm
leaving that for another day.

Test plan: Unit tests added.
This commit is contained in:
Dandelion Mané 2019-07-11 03:36:58 +01:00
parent a0b754bb43
commit b106326e0a
2 changed files with 20 additions and 1 deletions

View File

@ -48,6 +48,14 @@ export function defaultWeights(): Weights {
};
}
export function copy(w: Weights): Weights {
return {
nodeTypeWeights: new Map(w.nodeTypeWeights),
edgeTypeWeights: new Map(w.edgeTypeWeights),
nodeManualWeights: new Map(w.nodeManualWeights),
};
}
export type WeightsJSON = Compatible<{|
+nodeTypeWeights: {[NodeAddressT]: NodeWeight},
+edgeTypeWeights: {[EdgeAddressT]: EdgeWeight},

View File

@ -2,9 +2,20 @@
import stringify from "json-stable-stringify";
import {NodeAddress, EdgeAddress} from "../core/graph";
import {toJSON, fromJSON, defaultWeights} from "./weights";
import {toJSON, fromJSON, defaultWeights, copy} from "./weights";
describe("analysis/weights", () => {
it("copy makes a copy", () => {
const w = defaultWeights();
const w1 = copy(w);
w1.nodeTypeWeights.set(NodeAddress.empty, 33);
w1.edgeTypeWeights.set(EdgeAddress.empty, {forwards: 34, backwards: 39});
w1.nodeManualWeights.set(NodeAddress.empty, 35);
expect(w1).not.toEqual(w);
expect(w1.nodeTypeWeights).not.toEqual(w.nodeTypeWeights);
expect(w1.edgeTypeWeights).not.toEqual(w.edgeTypeWeights);
expect(w1.nodeManualWeights).not.toEqual(w.nodeManualWeights);
});
describe("toJSON/fromJSON", () => {
it("works for the default weights", () => {
const weights = defaultWeights();