utils.js 899 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. const {inspect} = require('util');
  2. /////////////////////////////////////////////////////////////
  3. // Returns {line, column} of an index within multi-line text.
  4. function getIndexPos(text, index) {
  5. let lineIdx = 0, colIdx = index, pos = 0;
  6. do {
  7. pos = text.indexOf('\n', pos);
  8. if (pos === -1 || index < pos + 1) {
  9. break;
  10. }
  11. lineIdx++;
  12. pos++;
  13. colIdx = index - pos;
  14. } while (pos < index);
  15. return {
  16. line: lineIdx + 1,
  17. column: colIdx + 1
  18. };
  19. }
  20. ///////////////////////////////////////////
  21. // Returns a space gap for console output.
  22. function messageGap(level) {
  23. return ' '.repeat(level * 4);
  24. }
  25. ////////////////////////////////////////////////////
  26. // Type inspection
  27. function addInspection(type, cb) {
  28. type[inspect.custom] = cb;
  29. }
  30. module.exports = {
  31. getIndexPos,
  32. messageGap,
  33. addInspection
  34. };