保誠-保戶業務員媒合平台
HelenHuang
2022-06-09 9bdb95c9e34cef640534e5e5a1e2225a80442000
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
const Node = require('./node');
 
class Container extends Node {
  walk(callback) {
    return this.each((child, i) => {
      let result = callback(child, i);
      if (result !== false && child.walk) {
        result = child.walk(callback);
      }
      return result;
    });
  }
 
  walkType(type, callback) {
    if (!type || !callback) {
      throw new Error('Parameters {type} and {callback} are required.');
    }
 
    // allow users to pass a constructor, or node type string; eg. Word.
    const isTypeCallable = typeof type === 'function';
 
    return this.walk((node, index) => {
      if ((isTypeCallable && node instanceof type) || (!isTypeCallable && node.type === type)) {
        return callback.call(this, node, index);
      }
    });
  }
}
 
Container.registerWalker = (constructor) => {
  let walkerName = `walk${constructor.name}`;
 
  // plural sugar
  if (walkerName.lastIndexOf('s') !== walkerName.length - 1) {
    walkerName += 's';
  }
 
  if (Container.prototype[walkerName]) {
    return;
  }
 
  // we need access to `this` so we can't use an arrow function
  Container.prototype[walkerName] = function(callback) {
    return this.walkType(constructor, callback);
  };
};
 
module.exports = Container;