Last active
December 20, 2017 01:16
-
-
Save dfkaye/87895e1ee2c297429214 to your computer and use it in GitHub Desktop.
fluent arithmetic operators
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
// 9 July 2015 | |
// operable: add, subtract, multiply, divide, remainder | |
// 19 Dec 2017: added valueOf() vs. toString() | |
function operable(value) { | |
var c = Object.create(operable.prototype); | |
c.toString = function() { | |
return '' + value; | |
}; | |
c.valueOf = function() { | |
return value; | |
}; | |
return c; | |
}; | |
operable.prototype = { | |
'add' : function add(n) { return isNaN(this) ? NaN : +this + n; }, | |
'subtract' : function subtract(n) { return this - n; }, | |
'multiply' : function multiply(n) { return this * n; }, | |
'divide' : function divide(n) { return this / n; }, | |
'remainder' : function remainder(n) { return this % n; } | |
}; | |
console.warn('*** operable ***'); | |
console.log( operable(0).add(-0) ); | |
console.log( operable(3).add(3) ); | |
console.log( operable(-3).subtract(3) ); | |
console.log( operable(-3).multiply(3) ); | |
console.log( operable(-3).divide(3) ); | |
console.log( operable(-9).remainder(4) ); | |
console.log( operable(1).add(true) ); | |
console.log( operable(false).add(false) ); // ? | |
console.log( operable(3).add('3') ); | |
console.log( operable(3).subtract('3') ); | |
console.log( operable(9.5).remainder('.75') ); | |
console.warn('*** Infinity ***'); | |
console.warn( operable(1).divide(0) ); | |
console.warn( operable(1).divide('0') ); | |
console.warn( operable('1').divide('0') ); | |
console.warn( operable('1').divide(0) ); | |
console.warn('*** NaN ***'); | |
console.log( operable('false').add(false) ); | |
console.log( operable('bogus').subtract(6) ); | |
console.log( operable(6).subtract('f') ); | |
console.log( operable(6).multiply('f') ); | |
console.log( operable(9.5).remainder('christ') ); | |
console.warn('*** toString vs. valueOf ***'); | |
console.log( operable(7).toString() === '7' ); | |
console.log( operable(7).valueOf() === 7); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment