把下面的代码使用babel转换

    1. // 前
    2. function* foo() {
    3. yield 'a';
    4. yield 'b';
    5. }
    1. // 后
    2. "use strict";
    3. var _marked = /*#__PURE__*/ regeneratorRuntime.mark(foo);
    4. function foo() {
    5. return regeneratorRuntime.wrap(function foo$(_context) {
    6. while (1) {
    7. switch ((_context.prev = _context.next)) {
    8. case 0:
    9. _context.next = 2;
    10. return "a";
    11. case 2:
    12. _context.next = 4;
    13. return "b";
    14. case 4:
    15. case "end":
    16. return _context.stop();
    17. }
    18. }
    19. }, _marked);
    20. }

    实现思路:
    实现regeneratorRuntime.wrap函数,context保存状态

    1. // regeneratorRuntime.wrap
    2. function generator(cb) {
    3. const context = {
    4. next: 0,
    5. prev: 0,
    6. stop: function() {
    7. // return undefind
    8. }
    9. }
    10. return {
    11. next: function() {
    12. let ret = cb(context)
    13. if (ret === undefined) {
    14. return { value: undefined, done: true };
    15. }
    16. return {
    17. value: ret,
    18. done: false
    19. }
    20. }
    21. }
    22. }
    23. function foo() {
    24. return generator(function foo$(_context) {
    25. while (1) {
    26. switch ((_context.prev = _context.next)) {
    27. case 0:
    28. _context.next = 2;
    29. return "a";
    30. case 2:
    31. _context.next = 4;
    32. return "b";
    33. case 4:
    34. case "end":
    35. return _context.stop();
    36. }
    37. }
    38. });
    39. }

    image.png