position-algerbra.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * MIT License http://opensource.org/licenses/MIT
  3. * Author: Ben Holloway @bholloway
  4. */
  5. 'use strict';
  6. /**
  7. * Given a sourcemap position create a new maybeObject with only line and column properties.
  8. *
  9. * @param {*|{line: number, column: number}} maybeObj Possible location hash
  10. * @returns {{line: number, column: number}} Location hash with possible NaN values
  11. */
  12. function sanitise(maybeObj) {
  13. var obj = !!maybeObj && typeof maybeObj === 'object' && maybeObj || {};
  14. return {
  15. line: isNaN(obj.line) ? NaN : obj.line,
  16. column: isNaN(obj.column) ? NaN : obj.column
  17. };
  18. }
  19. exports.sanitise = sanitise;
  20. /**
  21. * Infer a line and position delta based on the linebreaks in the given string.
  22. *
  23. * @param candidate {string} A string with possible linebreaks
  24. * @returns {{line: number, column: number}} A position object where line and column are deltas
  25. */
  26. function strToOffset(candidate) {
  27. var split = candidate.split(/\r\n|\n/g);
  28. var last = split[split.length - 1];
  29. return {
  30. line: split.length - 1,
  31. column: last.length
  32. };
  33. }
  34. exports.strToOffset = strToOffset;
  35. /**
  36. * Add together a list of position elements.
  37. *
  38. * Lines are added. If the new line is zero the column is added otherwise it is overwritten.
  39. *
  40. * @param {{line: number, column: number}[]} list One or more sourcemap position elements to add
  41. * @returns {{line: number, column: number}} Resultant position element
  42. */
  43. function add(list) {
  44. return list
  45. .slice(1)
  46. .reduce(
  47. function (accumulator, element) {
  48. return {
  49. line: accumulator.line + element.line,
  50. column: element.line > 0 ? element.column : accumulator.column + element.column,
  51. };
  52. },
  53. list[0]
  54. );
  55. }
  56. exports.add = add;