stop.js 990 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var assert = require('assert');
  2. var traverse = require('traverse');
  3. exports.stop = function () {
  4. var visits = 0;
  5. traverse('abcdefghij'.split('')).forEach(function (node) {
  6. if (typeof node === 'string') {
  7. visits ++;
  8. if (node === 'e') this.stop()
  9. }
  10. });
  11. assert.equal(visits, 5);
  12. };
  13. exports.stopMap = function () {
  14. var s = traverse('abcdefghij'.split('')).map(function (node) {
  15. if (typeof node === 'string') {
  16. if (node === 'e') this.stop()
  17. return node.toUpperCase();
  18. }
  19. }).join('');
  20. assert.equal(s, 'ABCDEfghij');
  21. };
  22. exports.stopReduce = function () {
  23. var obj = {
  24. a : [ 4, 5 ],
  25. b : [ 6, [ 7, 8, 9 ] ]
  26. };
  27. var xs = traverse(obj).reduce(function (acc, node) {
  28. if (this.isLeaf) {
  29. if (node === 7) this.stop();
  30. else acc.push(node)
  31. }
  32. return acc;
  33. }, []);
  34. assert.deepEqual(xs, [ 4, 5, 6 ]);
  35. };