Reputation: 1
I am working on a project and need to implement a function called magic_inc that increments or decrements a given value based on a specific logic. The goal of this function is to apply a custom sequence of increments or decrements to the input value. Here's the sequence:
Upvotes: -1
Views: 101
Reputation: 12657
I'd utilize scientific notation to quickly get the coefficient and the exponent.
Cleanup: truncate the coefficient to an int.
Then just take care of the special cases like 1 -> 0.9
and -0.9 -> -1
otherwise increment/decrement the coefficient.
function magic_inc(value, mode) {
if (typeof value !== 'number' || value === 0) {
return 0;
}
let [a,b] = value.toExponential().toLowerCase().split("e");
a = parseInt(a, 10);
if(mode === "inc") a = a===-1 ? -.9 : a+1;
if(mode === "dec") a = a===1 ? .9 : a-1;
return +`${a}e${b}`;
}
console.log(magic_inc(0.5, 'inc')); // Output: 0.6
console.log(magic_inc(-0.3, 'inc')); // Output: -0.2
console.log(magic_inc(1568.548, 'inc')); // Output: 2000
console.log(magic_inc(17, 'dec')); // Output: 9
Upvotes: 1