Skip to content

Instantly share code, notes, and snippets.

@westc
Last active June 28, 2023 04:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save westc/025d8ff780f8d524086ab44760fe9975 to your computer and use it in GitHub Desktop.
Efficient isNegative(), isPositive(), sameSign() and copySign() functions.
function copySign(toUpdate, signedNum) {
return toUpdate + 1 / toUpdate < 0 === signedNum + 1 / signedNum < 0
? toUpdate
: -toUpdate;
}
function isNegative(x, opt_includeZero) {
return (opt_includeZero ? x + 1 / x : x) < 0;
}
function isPositive(x, opt_includeZero) {
return (opt_includeZero ? x + 1 / x : x) > 0;
}
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;
}
// 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);
}
@westc
Copy link
Author

westc commented Jun 28, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment