forked from jonschlinkert/is-number
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (81 loc) · 2.19 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const { Suite } = require('benchmark');
const cursor = require('ansi')(process.stdout);
const fixtures = require('./fixtures');
const cycle = (e, nl) => {
cursor.eraseLine();
cursor.horizontalAbsolute();
cursor.write('' + e.target);
if (nl) cursor.write('\n');
};
function bench(name) {
const suite = new Suite()
.on('start', () => console.log(`# ${name}`))
.on('complete', function(e) {
const fastest = this.filter('fastest').map('name').toString();
console.log(`fastest is '${fastest}'`);
console.log();
})
const res = {
run: suite.run.bind(suite),
add(key, fn) {
suite.add(key, {
onCycle: e => cycle(e),
onComplete: e => cycle(e, true),
fn
});
return res;
}
};
return res;
}
function run(fn, prop = 'all') {
[].concat(fixtures[prop]).forEach(val => fn(val));
}
bench('all')
.add('v6.1', () => run(isNumber61))
.add('v6.0', () => run(isNumber60))
.add('parseFloat', () => run(isNumberParseFloat))
.run()
bench('string')
.add('v6.1', () => run(isNumber61, 'string'))
.add('v6.0', () => run(isNumber60, 'string'))
.add('parseFloat', () => run(isNumberParseFloat, 'string'))
.run()
bench('number')
.add('v6.1', () => run(isNumber61, 'number'))
.add('v6.0', () => run(isNumber60, 'number'))
.add('parseFloat', () => run(isNumberParseFloat, 'number'))
.run()
function isNumberParseFloat(n) {
if (typeof num === 'number') {
return num - num === 0;
}
if (typeof num === 'string') {
return (num - parseFloat(num)) > -1;
}
return false;
}
function isNumber60(val) {
let number = +val;
// Discard Infinity and NaN
if ((number - number) !== 0) return false;
if (number === val) return true;
if (typeof val === 'string') {
// whitespace and empty strings are coerced to 0
// If number is 0, trim the string to see if its empty.
if (number === 0 && val.trim() === '') {
return false;
}
return true;
}
return false;
}
function isNumber61(val) {
if (typeof num === 'number') {
return num - num === 0;
}
if (typeof num === 'string' && num.trim() !== '') {
return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
}
return false;
}