replaceShorthandObjectMethod.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import * as t from "babel-types";
  2. import * as util from "./util";
  3. // this function converts a shorthand object generator method into a normal
  4. // (non-shorthand) object property which is a generator function expression. for
  5. // example, this:
  6. //
  7. // var foo = {
  8. // *bar(baz) { return 5; }
  9. // }
  10. //
  11. // should be replaced with:
  12. //
  13. // var foo = {
  14. // bar: function*(baz) { return 5; }
  15. // }
  16. //
  17. // to do this, it clones the parameter array and the body of the object generator
  18. // method into a new FunctionExpression.
  19. //
  20. // this method can be passed any Function AST node path, and it will return
  21. // either:
  22. // a) the path that was passed in (iff the path did not need to be replaced) or
  23. // b) the path of the new FunctionExpression that was created as a replacement
  24. // (iff the path did need to be replaced)
  25. //
  26. // In either case, though, the caller can count on the fact that the return value
  27. // is a Function AST node path.
  28. //
  29. // If this function is called with an AST node path that is not a Function (or with an
  30. // argument that isn't an AST node path), it will throw an error.
  31. export default function replaceShorthandObjectMethod(path) {
  32. if (!path.node || !t.isFunction(path.node)) {
  33. throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths.");
  34. }
  35. // this function only replaces shorthand object methods (called ObjectMethod
  36. // in Babel-speak).
  37. if (!t.isObjectMethod(path.node)) {
  38. return path;
  39. }
  40. // this function only replaces generators.
  41. if (!path.node.generator) {
  42. return path;
  43. }
  44. const parameters = path.node.params.map(function (param) {
  45. return t.cloneDeep(param);
  46. })
  47. const functionExpression = t.functionExpression(
  48. null, // id
  49. parameters, // params
  50. t.cloneDeep(path.node.body), // body
  51. path.node.generator,
  52. path.node.async
  53. );
  54. util.replaceWithOrRemove(path,
  55. t.objectProperty(
  56. t.cloneDeep(path.node.key), // key
  57. functionExpression, //value
  58. path.node.computed, // computed
  59. false // shorthand
  60. )
  61. );
  62. // path now refers to the ObjectProperty AST node path, but we want to return a
  63. // Function AST node path for the function expression we created. we know that
  64. // the FunctionExpression we just created is the value of the ObjectProperty,
  65. // so return the "value" path off of this path.
  66. return path.get("value");
  67. }