Skip to content

Commit 7c9a891

Browse files
committed
Use isArray instead of constructor check - fixes #28
1 parent 4efbfd1 commit 7c9a891

3 files changed

Lines changed: 40 additions & 2 deletions

File tree

array.test.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,43 @@
11
import * as array from './array.js'
22
import * as t from './testing.js'
33

4+
/**
5+
* @param {t.TestCase} _tc
6+
*/
7+
export const testIsarrayPerformance = _tc => {
8+
const N = 100000
9+
/**
10+
* @type {Array<any>}
11+
*/
12+
const objects = []
13+
for (let i = 0; i < N; i++) {
14+
if (i % 2 === 0) {
15+
objects.push([i])
16+
} else {
17+
objects.push({ i })
18+
}
19+
}
20+
const timeConstructor = t.measureTime('constructor check', () => {
21+
let collectedArrays = 0
22+
objects.forEach(obj => {
23+
if (obj.constructor === Array) {
24+
collectedArrays++
25+
}
26+
})
27+
t.assert(collectedArrays === N / 2)
28+
})
29+
const timeIsarray = t.measureTime('Array.isArray', () => {
30+
let collectedArrays = 0
31+
objects.forEach(obj => {
32+
if (array.isArray(obj)) {
33+
collectedArrays++
34+
}
35+
})
36+
t.assert(collectedArrays === N / 2)
37+
})
38+
t.assert(timeIsarray < timeConstructor * 1.3, 'Expecting that isArray is not much worse than a constructor check')
39+
}
40+
441
/**
542
* @param {t.TestCase} _tc
643
*/

encoding.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import * as math from './math.js'
3131
import * as number from './number.js'
3232
import * as binary from './binary.js'
3333
import * as string from './string.js'
34+
import * as array from './array.js'
3435

3536
/**
3637
* A BinaryEncoder handles the encoding to an Uint8Array.
@@ -513,7 +514,7 @@ export const writeAny = (encoder, data) => {
513514
if (data === null) {
514515
// TYPE 126: null
515516
write(encoder, 126)
516-
} else if (data instanceof Array) {
517+
} else if (array.isArray(data)) {
517518
// TYPE 117: Array
518519
write(encoder, 117)
519520
writeVarUint(encoder, data.length)

function.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ export const equalityStrict = (a, b) => a === b
5858
* @param {Array<T>|object} b
5959
* @return {boolean}
6060
*/
61-
export const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((a instanceof Array && array.equalFlat(a, /** @type {Array<T>} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))
61+
export const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array<T>} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))
6262

6363
/* c8 ignore start */
6464

0 commit comments

Comments
 (0)