Skip to content

Instantly share code, notes, and snippets.

@JimOKelly
Created May 24, 2016 06:28
Show Gist options
  • Save JimOKelly/929beaa4caa442a66f29fc22f8f80204 to your computer and use it in GitHub Desktop.
Save JimOKelly/929beaa4caa442a66f29fc22f8f80204 to your computer and use it in GitHub Desktop.
Javascript based dominoes
var Node = function(a, b) {
this.data = {a: a, b: b };
this.parent = undefined;
this.children = [];
return this;
};
Node.prototype.isSpinner = function() {
return this.data.a === this.data.b;
};
Node.prototype.score = function() {
if (this.isSpinner() && this.children.length < 2) {
return (this.data.a + this.data.b);
}
if (this.children.length === 0) {
return (this.parent.data.b == this.data.b) ? this.data.a : this.data.b;
}
return 0;
};
Node.prototype.add = function(a, b) {
var child = new Node(a, b);
this.children.push(child);
child.parent = this;
return child;
};
Node.prototype.traverse = function(done) {
(function recurse(curr) {
for (var i = 0, length = curr.children.length; i < length; i++) {
recurse(curr.children[i]);
}
done(curr);
}(this));
};
var spinner = new Node(6, 6);
var node = spinner.add(6, 3);
// node = node.add(3, 5);
// node = spinner.add(6, 0);
// node = node.add(0, 3);
// node = spinner.add(6, 5);
// node = spinner.add(6, 2);
var scores = [];
spinner.traverse(function(n) {
scores.push(n.score());
});
var sum = function(vals) {
result = vals.reduce(function(acc, val) {
return acc + val;
});
return (result % 5 === 0) ? result : 0;
};
console.log(sum(scores));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment