whitespace.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. "use strict";
  2. exports.__esModule = true;
  3. var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
  4. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  5. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6. var Whitespace = function () {
  7. function Whitespace(tokens) {
  8. (0, _classCallCheck3.default)(this, Whitespace);
  9. this.tokens = tokens;
  10. this.used = {};
  11. }
  12. Whitespace.prototype.getNewlinesBefore = function getNewlinesBefore(node) {
  13. var startToken = void 0;
  14. var endToken = void 0;
  15. var tokens = this.tokens;
  16. var index = this._findToken(function (token) {
  17. return token.start - node.start;
  18. }, 0, tokens.length);
  19. if (index >= 0) {
  20. while (index && node.start === tokens[index - 1].start) {
  21. --index;
  22. }startToken = tokens[index - 1];
  23. endToken = tokens[index];
  24. }
  25. return this._getNewlinesBetween(startToken, endToken);
  26. };
  27. Whitespace.prototype.getNewlinesAfter = function getNewlinesAfter(node) {
  28. var startToken = void 0;
  29. var endToken = void 0;
  30. var tokens = this.tokens;
  31. var index = this._findToken(function (token) {
  32. return token.end - node.end;
  33. }, 0, tokens.length);
  34. if (index >= 0) {
  35. while (index && node.end === tokens[index - 1].end) {
  36. --index;
  37. }startToken = tokens[index];
  38. endToken = tokens[index + 1];
  39. if (endToken && endToken.type.label === ",") endToken = tokens[index + 2];
  40. }
  41. if (endToken && endToken.type.label === "eof") {
  42. return 1;
  43. } else {
  44. return this._getNewlinesBetween(startToken, endToken);
  45. }
  46. };
  47. Whitespace.prototype._getNewlinesBetween = function _getNewlinesBetween(startToken, endToken) {
  48. if (!endToken || !endToken.loc) return 0;
  49. var start = startToken ? startToken.loc.end.line : 1;
  50. var end = endToken.loc.start.line;
  51. var lines = 0;
  52. for (var line = start; line < end; line++) {
  53. if (typeof this.used[line] === "undefined") {
  54. this.used[line] = true;
  55. lines++;
  56. }
  57. }
  58. return lines;
  59. };
  60. Whitespace.prototype._findToken = function _findToken(test, start, end) {
  61. if (start >= end) return -1;
  62. var middle = start + end >>> 1;
  63. var match = test(this.tokens[middle]);
  64. if (match < 0) {
  65. return this._findToken(test, middle + 1, end);
  66. } else if (match > 0) {
  67. return this._findToken(test, start, middle);
  68. } else if (match === 0) {
  69. return middle;
  70. }
  71. return -1;
  72. };
  73. return Whitespace;
  74. }();
  75. exports.default = Whitespace;
  76. module.exports = exports["default"];