trailing-comma-visitors.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Copyright 2013-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. */
  9. var Syntax = require('esprima-fb').Syntax;
  10. var utils = require('../src/utils');
  11. /**
  12. * Strips trailing commas from array and object expressions. Transforms:
  13. *
  14. * var arr = [
  15. * foo,
  16. * bar,
  17. * ];
  18. *
  19. * var obj = {
  20. * foo: 1,
  21. * bar: 2,
  22. * };
  23. *
  24. * into:
  25. *
  26. * var arr = [
  27. * foo,
  28. * bar
  29. * ];
  30. *
  31. * var obj = {
  32. * foo: 1,
  33. * bar: 2
  34. * };
  35. *
  36. */
  37. function visitArrayOrObjectExpression(traverse, node, path, state) {
  38. var items = node.elements || node.properties;
  39. var lastItem = items[items.length - 1];
  40. // Transform items if needed.
  41. path.unshift(node);
  42. traverse(items, path, state);
  43. path.shift();
  44. // Catch up to the end of the last item.
  45. utils.catchup(lastItem.range[1], state);
  46. // Strip any non-whitespace between the last item and the end.
  47. utils.catchup(node.range[1] - 1, state, function(value) {
  48. return value.replace(/,/g, '');
  49. });
  50. return false;
  51. }
  52. visitArrayOrObjectExpression.test = function(node, path, state) {
  53. return (node.type === Syntax.ArrayExpression ||
  54. node.type === Syntax.ObjectExpression) &&
  55. (node.elements || node.properties).length > 0 &&
  56. // We don't want to run the transform on arrays with trailing holes, since
  57. // it would change semantics.
  58. !hasTrailingHole(node);
  59. };
  60. function hasTrailingHole(node) {
  61. return node.elements && node.elements.length > 0 &&
  62. node.elements[node.elements.length - 1] === null;
  63. }
  64. exports.visitorList = [
  65. visitArrayOrObjectExpression
  66. ];