File tree 2 files changed +34
-1
lines changed
2 files changed +34
-1
lines changed Original file line number Diff line number Diff line change
1
+ import filterObj from 'filter-obj' ;
2
+
3
+ // Benchmark `filter-obj`.
4
+ // Higher `loopCount` give more precise results but last longer.
5
+ // `objectSize` gives different results based on how big the input object is.
6
+ // `predicateSize` is similar but for predicate arrays. When `undefined`, a predicate function is used instead.
7
+ const benchmark = function ( loopCount , objectSize , predicateSize ) {
8
+ const bigObject = Object . fromEntries ( Array . from ( { length : objectSize } , getObjectKeyPair ) ) ;
9
+ const predicate = predicateSize === undefined ? isEven : Array . from ( { length : predicateSize } , getPredicateKey ) ;
10
+
11
+ console . time ( ) ;
12
+ for ( let index = 0 ; index < loopCount ; index += 1 ) {
13
+ filterObj ( bigObject , predicate ) ;
14
+ }
15
+
16
+ console . timeEnd ( ) ;
17
+ } ;
18
+
19
+ const getObjectKeyPair = function ( _ , index ) {
20
+ return [ `a${ index } ` , index ] ;
21
+ } ;
22
+
23
+ const getPredicateKey = function ( _ , index ) {
24
+ return `a${ index } ` ;
25
+ } ;
26
+
27
+ const isEven = function ( key , value ) {
28
+ return value % 2 === 0 ;
29
+ } ;
30
+
31
+ benchmark ( 1e3 , 1e4 ) ;
Original file line number Diff line number Diff line change @@ -15,7 +15,9 @@ export default function filterObject(object, predicate) {
15
15
}
16
16
}
17
17
} else {
18
- for ( const [ key , value ] of Object . entries ( object ) ) {
18
+ // `for ... of Object.keys()` is faster than `for ... of Object.entries()`.
19
+ for ( const key of Object . keys ( object ) ) {
20
+ const value = object [ key ] ;
19
21
if ( predicate ( key , value , object ) ) {
20
22
Object . defineProperty ( result , key , {
21
23
value,
You can’t perform that action at this time.
0 commit comments