22
33const parser = require ( '@babel/parser' ) ;
44
5+ function isObject ( str ) {
6+ return typeof str === 'object' && ! Array . isArray ( str ) && str !== null ;
7+ }
8+
59/**
610 * @param {Object } options - Options to configure parser
711 * @param {Object } options.parser - An object with a parse method that returns an AST
@@ -68,21 +72,21 @@ module.exports.prototype.traverse = function(node, cb) {
6872
6973 if ( Array . isArray ( node ) ) {
7074 for ( const key of node ) {
71- if ( key !== null && typeof key === 'object' ) {
75+ if ( isObject ( key ) ) {
7276 // Mark that the node has been visited
7377 key . parent = node ;
7478 this . traverse ( key , cb ) ;
7579 }
7680 }
77- } else if ( node && typeof node === 'object' ) {
81+ } else if ( node && isObject ( node ) ) {
7882 cb ( node ) ;
7983
8084 // TODO switch to Object.entries
8185 for ( const key of Object . keys ( node ) ) {
8286 // Avoid visited nodes
8387 if ( key === 'parent' || ! node [ key ] ) continue ;
8488
85- if ( typeof node [ key ] === 'object' ) {
89+ if ( isObject ( node [ key ] ) ) {
8690 node [ key ] . parent = node ;
8791 }
8892
@@ -101,17 +105,15 @@ module.exports.prototype.traverse = function(node, cb) {
101105module . exports . prototype . walk = function ( src , cb ) {
102106 this . shouldStop = false ;
103107
104- const ast = typeof src === 'object' ? src : this . parse ( src ) ;
108+ const ast = isObject ( src ) ? src : this . parse ( src ) ;
105109
106110 this . traverse ( ast , cb ) ;
107111} ;
108112
109113module . exports . prototype . moonwalk = function ( node , cb ) {
110114 this . shouldStop = false ;
111115
112- if ( typeof node !== 'object' ) {
113- throw new Error ( 'node must be an object' ) ;
114- }
116+ if ( ! isObject ( node ) ) throw new Error ( 'node must be an object' ) ;
115117
116118 reverseTraverse . call ( this , node , cb ) ;
117119} ;
0 commit comments