From 024345829b06638a9cd036e48ad08c60cb074fb4 Mon Sep 17 00:00:00 2001 From: Fen Dweller Date: Sun, 18 Feb 2018 14:18:14 -0500 Subject: [PATCH] Merging is now done all the way! Should function correctly for arbitrarily nested objects --- game.js | 2 +- recursive-macro.js | 43 +++++++++++++++++++++++++++---------------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/game.js b/game.js index b44c34c..d421950 100644 --- a/game.js +++ b/game.js @@ -229,7 +229,7 @@ function doDigest(containerName) var toDigest = digestType.shift(); if (toDigest.name != "Container") toDigest = new Container([toDigest]); - container.merge(toDigest); + container = container.merge(toDigest); } var digested = container.sum(); diff --git a/recursive-macro.js b/recursive-macro.js index adb4116..a344f51 100644 --- a/recursive-macro.js +++ b/recursive-macro.js @@ -175,6 +175,32 @@ function defaultMass(thing) { return masses[thing.name]; } +function defaultMerge(thing) { + return function(container) { + var newCount = this.count + container.count; + + var newThing = new things[thing.name](newCount); + newThing.contents = {}; + + for (var key in this.contents) { + if (this.contents.hasOwnProperty(key)) { + newThing.contents[key] = this.contents[key]; + } + } + + for (var key in container.contents) { + if (container.contents.hasOwnProperty(key)) { + if (this.contents.hasOwnProperty(key)) { + newThing.contents[key] = this.contents[key].merge(container.contents[key]); + } else {; + newThing.contents[key] = container.contents[key]; + } + } + } + + return newThing; + } +} function defaultSum(thing) { return function() { @@ -224,6 +250,7 @@ function DefaultEntity() { this.area = defaultArea; this.mass = defaultMass; this.sum_property = defaultSumProperty; + this.merge = defaultMerge; return this; } @@ -260,22 +287,6 @@ function Container(contents = []) { return describe_all(this.contents) } - // put another container into this one - - this.merge = function(container) { - for (var key in container.contents) { - if (container.contents.hasOwnProperty(key)) { - if (this.contents.hasOwnProperty(key)) { - this.count += container.contents[key].count; - this.contents[key] = new things[container.contents[key].name](container.contents[key].count + this.contents[key].count); - } else { - this.count += container.contents[key].count; - this.contents[key] = new things[container.contents[key].name](container.contents[key].count); - } - } - } - } - return this; }