Add more tests to isPositive() bitwise function.

This commit is contained in:
Oleksii Trekhleb 2018-09-14 08:06:48 +03:00
parent ab7755aad7
commit 92b9e6ad1d
3 changed files with 16 additions and 14 deletions

View File

@ -53,10 +53,9 @@ isEven: true
#### isPositive
This method determines if the number provided is positive.
It is based on the fact that all positive numbers have their last
left bit to be set to 0. However, if the number provided is zero
or negative zero, it should still return false.
This method determines if the number is positive. It is based on the fact that all positive
numbers have their leftmost bit to be set to `0`. However, if the number provided is zero
or negative zero, it should still return `false`.
```text
Number: 1 = 0b0001
@ -64,12 +63,6 @@ isPositive: true
Number: -1 = -0b0001
isPositive: false
Number: 0 = 0b0000
isPositive: false
Number: -0 = 0b0000
isPositive: false
```
> See [isPositive.js](isPositive.js) for further details.

View File

@ -2,9 +2,18 @@ import isPositive from '../isPositive';
describe('isPositive', () => {
it('should detect if a number is positive', () => {
expect(isPositive(1)).toBe(true);
expect(isPositive(2)).toBe(true);
expect(isPositive(3)).toBe(true);
expect(isPositive(5665)).toBe(true);
expect(isPositive(56644325)).toBe(true);
expect(isPositive(0)).toBe(false);
expect(isPositive(-0)).toBe(false);
expect(isPositive(1)).toBe(true);
expect(isPositive(-1)).toBe(false);
expect(isPositive(-2)).toBe(false);
expect(isPositive(-126)).toBe(false);
expect(isPositive(-5665)).toBe(false);
expect(isPositive(-56644325)).toBe(false);
});
});

View File

@ -1,13 +1,13 @@
/**
* @param {number} number
* @param {number} number - 32-bit integer.
* @return {boolean}
*/
export default function isPositive(number) {
// Zero is neither a positive nor a negative number
// Zero is neither a positive nor a negative number.
if (number === 0) {
return false;
}
// The most signification bit can be used to determine whether .
// The most significant 32nd bit can be used to determine whether the number is positive.
return ((number >> 31) & 1) === 0;
}