Skip to content

Commit

Permalink
fix: Treat NaN as -infinity for sorting
Browse files Browse the repository at this point in the history
* A couple of test cases with NaN's thrown in 

The first of these fails for me, I think its due to your sort method

* Treat NaN as -infinity for sorting

* Updated readme to make a note on NaN
  • Loading branch information
lukemcgregor authored and d4rkr00t committed Jul 5, 2018
1 parent 060a384 commit 4bcf3fd
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -37,6 +37,9 @@ var result = percentile(
console.log(result); // 8

```
## Notes

Non-numeric (NaN) values are treated as the smallest values, Eg `percentile(50, [ 5, 2, NaN]) === 2`

## Author

Expand Down
3 changes: 3 additions & 0 deletions lib/index.js
Expand Up @@ -61,6 +61,9 @@ function percentile(p, list, fn) {
b = fn(b);
}

a = Number.isNaN(a) ? Number.NEGATIVE_INFINITY : a;
b = Number.isNaN(b) ? Number.NEGATIVE_INFINITY : b;

if (a > b) return 1;
if (a < b) return -1;

Expand Down
2 changes: 2 additions & 0 deletions test/index.js
Expand Up @@ -24,6 +24,8 @@ const stubsSimple = [
{ percentile: 75, list: shuffleArray(generateArraySimple(100)), result: 75 },
{ percentile: 100, list: shuffleArray(generateArraySimple(100)), result: 100 },

{ percentile: 75, list: [NaN, NaN, 1, 100], result: 1 },
{ percentile: 75, list: [1, 100, NaN, NaN], result: 1 },
{ percentile: 75, list: shuffleArray([].concat(generateArraySimple(100), generateArraySimple(30))), result: 68 }
];

Expand Down

0 comments on commit 4bcf3fd

Please sign in to comment.