web 3d图形渲染器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.2 KiB

  1. const Node = require('./node');
  2. class Container extends Node {
  3. walk(callback) {
  4. return this.each((child, i) => {
  5. let result = callback(child, i);
  6. if (result !== false && child.walk) {
  7. result = child.walk(callback);
  8. }
  9. return result;
  10. });
  11. }
  12. walkType(type, callback) {
  13. if (!type || !callback) {
  14. throw new Error('Parameters {type} and {callback} are required.');
  15. }
  16. // allow users to pass a constructor, or node type string; eg. Word.
  17. const isTypeCallable = typeof type === 'function';
  18. return this.walk((node, index) => {
  19. if ((isTypeCallable && node instanceof type) || (!isTypeCallable && node.type === type)) {
  20. return callback.call(this, node, index);
  21. }
  22. });
  23. }
  24. }
  25. Container.registerWalker = (constructor) => {
  26. let walkerName = `walk${constructor.name}`;
  27. // plural sugar
  28. if (walkerName.lastIndexOf('s') !== walkerName.length - 1) {
  29. walkerName += 's';
  30. }
  31. if (Container.prototype[walkerName]) {
  32. return;
  33. }
  34. // we need access to `this` so we can't use an arrow function
  35. Container.prototype[walkerName] = function(callback) {
  36. return this.walkType(constructor, callback);
  37. };
  38. };
  39. module.exports = Container;