Created
December 25, 2021 16:19
-
-
Save elvan/ccea093a8cbb866119477254b1f15724 to your computer and use it in GitHub Desktop.
Method chaining for numbers without polluting prototype
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 MyNumber(n) { | |
var internal = Number(n); | |
this.multiply = function(n) { | |
return internal * n | |
} | |
this.divide = function(n) { | |
return internal / n | |
} | |
this.subtract = function(n) { | |
return internal - n | |
} | |
this.add = function(n) { | |
return internal + n | |
} | |
} | |
const operation = (n) => { | |
return new MyNumber(n) | |
} | |
const result = operation(10) | |
.multiply(2) | |
.divide(10) | |
.subtract(3) | |
.add(10) | |
.divide(2) | |
console.log(result) // 4.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment