Skip to content

Instantly share code, notes, and snippets.

@elvan
Created December 25, 2021 16:19
Show Gist options
  • Save elvan/ccea093a8cbb866119477254b1f15724 to your computer and use it in GitHub Desktop.
Save elvan/ccea093a8cbb866119477254b1f15724 to your computer and use it in GitHub Desktop.
Method chaining for numbers without polluting prototype
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