I have a method that calculate a percentage increase between two values.
And in my "class" it looks like this:
percIncrease(a, b) {
let percent;
if (b !== 0) {
if (a !== 0) {
percent = ((b - a) / a) * 100;
} else {
percent = b * 100;
}
} else {
percent = -a * 100;
}
return percent.toFixed(3);
}
now cause I want it reusable from everywhere, I am trying to define it on a type (Number), so I can use it everywhere.
I tried this:
Number.prototype.percIncrease = function (a, b) {
let percent;
if (b !== 0) {
if (a !== 0) {
percent = ((b - a) / a) * 100;
} else {
percent = b * 100;
}
} else {
percent = -a * 100;
}
return percent.toFixed(3);
};
but if I try to use it like this :
Number.percIncrease(a,b);
TypeError: Number.percIncrease is not a function
I am not that good in using Javascript terms, but what I am actually trying, is to declare a static method on a specific type (say, Number).
How I would do this?
EDIT:
Or it doesn’t have to be static. Working on a value would do the job to. For example this (pseudo code):
myNumber.percIncrease(inCompareToValue: anotherNumber)
>Solution :
When you define a method in the prototype, it’s used when you call the method on an instance. Static methods should be added to the type directly, not the prototype:
Number.percIncrease = function (a, b) {
let percent;
if (b !== 0) {
if (a !== 0) {
percent = ((b - a) / a) * 100;
} else {
percent = b * 100;
}
} else {
percent = -a * 100;
}
return percent.toFixed(3);
};
console.log(Number.percIncrease(10, 15));