Last active
December 15, 2015 14:19
-
-
Save ircmaxell/5273410 to your computer and use it in GitHub Desktop.
Math, using set operations in JavaScript. Why? Because `+` and `-` are just too hard to use... ProTip: don't use large numbers, unless you dislike your CPU... :-D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
var Unit = function(value) { | |
var elements = []; | |
if (value instanceof Array) { | |
elements = value.slice(); | |
} else { | |
for (var i = 0; i < value; i++) { | |
elements.push(1); | |
} | |
} | |
this.getValue = function() { | |
return elements.slice(); | |
} | |
this.toPrimitive = function() { | |
return elements.reduce(function(left, right) { return left + right; }, 0); | |
} | |
return this; | |
}; | |
var factory = function(value) { | |
if (value instanceof Unit) { | |
return value; | |
} | |
return new Unit(value); | |
}; | |
var Operations = { | |
add: function(left, right) { | |
return factory([].concat(factory(left).getValue(), factory(right).getValue())); | |
}, | |
subtract: function(left, right) { | |
return factory(factory(left).getValue().slice(factory(right).toPrimitive())); | |
}, | |
multiply: function(left, right) { | |
return factory(factory(left).getValue().reduce(function(l, r) { return factory(l.getValue().concat(factory(right).getValue()));}, factory(0))); | |
}, | |
power: function(base, exponent) { | |
return factory(exponent).getValue().reduce(function(l, r) { return Operations.multiply(l, factory(base)); }, factory(1)); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment