function copySign(toUpdate, signedNum) {
return toUpdate + 1 / toUpdate < 0 === signedNum + 1 / signedNum < 0
? toUpdate
: -toUpdate;
}
view raw copySign.js hosted with ❤ by GitHub
function isNegative(x, opt_includeZero) {
return (opt_includeZero ? x + 1 / x : x) < 0;
}
view raw isNegative.js hosted with ❤ by GitHub
function isPositive(x, opt_includeZero) {
return (opt_includeZero ? x + 1 / x : x) > 0;
}
view raw isPositive.js hosted with ❤ by GitHub
function sameSign() {
for (
// NOTE: Using var here for code optimization in Google Closure Compiler
var isPositive, number, numbers = arguments, i = numbers.length;
number = numbers[--i], i >= 0 && 'number' === typeof number && number === number;
) {
let newIsPositive = number + 1 / number > 0;
if (isPositive == null) isPositive = newIsPositive;
else if (isPositive !== newIsPositive) return false;
}
return i < 0;
}
view raw sameSign.js hosted with ❤ by GitHub
// Test isNegative() and isPositive()
let numbers = [0, 0.123456789, 1, 123456789, Infinity];
numbers = ['A'].concat([...numbers].reverse().map(x => -x), numbers, ['Z']);
for (const [name, fn] of [['isNegative', isNegative], ['isPositive', isPositive]]) {
for (const bool of [false, true]) {
for (const x of numbers) {
console.log(`${name}(${(x === 0 && 1/x < 0) ? '-0' : x}, ${bool}) => ${fn(x, bool)}`);
}
}
}
// Test sameSign()
for (const {args, result} of [
{args: ['-2'], result: false},
{args: ['2'], result: false},
{args: [-2], result: true},
{args: [2], result: true},
{args: [0, 0], result: true},
{args: [0, -0], result: false},
{args: [-0, 0], result: false},
{args: [-0, -0], result: true},
{args: [0, 0, {}], result: false},
{args: [{}, 0, 0], result: false},
{args: [-0, -0, {}], result: false},
{args: [{}, -0, -0], result: false},
]) {
console.assert(sameSign(...args) === result, 'Failed for', args);
}
view raw ~example-run.js hosted with ❤ by GitHub