Skip to content

Commit 319a59f

Browse files
committed
Refactor to improve bundle size
1 parent 8c8a0c3 commit 319a59f

File tree

2 files changed

+35
-32
lines changed

2 files changed

+35
-32
lines changed

index.js

+26-29
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,51 @@
11
'use strict'
22

3-
var flatmap = require('flatmap')
43
var convert = require('unist-util-is/convert')
54

65
module.exports = filter
76

8-
function filter(tree, options, test) {
9-
var is
10-
var cascade
11-
12-
if (!test) {
13-
test = options
14-
options = {}
15-
}
7+
var own = {}.hasOwnProperty
168

17-
cascade = options.cascade
18-
cascade = cascade === null || cascade === undefined ? true : cascade
19-
is = convert(test)
9+
function filter(tree, options, test) {
10+
var is = convert(test || options)
11+
var cascade = options.cascade == null ? true : options.cascade
2012

2113
return preorder(tree, null, null)
2214

2315
function preorder(node, index, parent) {
16+
var children
17+
var childIndex
18+
var result
2419
var next
20+
var key
2521

26-
if (!is(node, index, parent)) {
27-
return null
28-
}
29-
30-
next = Object.keys(node).reduce(reduce, {})
22+
if (!is(node, index, parent)) return null
3123

3224
if (node.children) {
33-
next.children = flatmap(node.children, map)
25+
children = []
26+
childIndex = -1
3427

35-
if (cascade && node.children.length > 0 && next.children.length === 0) {
36-
return null
28+
while (++childIndex < node.children.length) {
29+
result = preorder(node.children[childIndex], childIndex, node)
30+
31+
if (result) {
32+
children.push(result)
33+
}
3734
}
35+
36+
if (cascade && node.children.length && !children.length) return null
3837
}
3938

40-
return next
39+
// Create a shallow clone, using the new children.
40+
next = {}
4141

42-
function reduce(acc, key) {
43-
if (key !== 'children') {
44-
acc[key] = node[key]
42+
for (key in node) {
43+
/* istanbul ignore else - Prototype injection. */
44+
if (own.call(node, key)) {
45+
next[key] = key === 'children' ? children : node[key]
4546
}
46-
47-
return acc
4847
}
4948

50-
function map(child, index) {
51-
return preorder(child, index, node)
52-
}
49+
return next
5350
}
5451
}

package.json

+9-3
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030
],
3131
"types": "types/index.d.ts",
3232
"dependencies": {
33-
"flatmap": "0.0.3",
3433
"unist-util-is": "^4.0.0"
3534
},
3635
"devDependencies": {
@@ -69,8 +68,15 @@
6968
"prettier": true,
7069
"esnext": false,
7170
"rules": {
72-
"unicorn/no-fn-reference-in-iterator": "off",
73-
"unicorn/no-reduce": "off"
71+
"eqeqeq": [
72+
"error",
73+
"always",
74+
{
75+
"null": "ignore"
76+
}
77+
],
78+
"no-eq-null": "off",
79+
"unicorn/explicit-length-check": "off"
7480
},
7581
"ignores": [
7682
"unist-util-position.js"

0 commit comments

Comments
 (0)