traverse.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. function traverseTable(dir, position, tableGrid, callback) {
  2. let result;
  3. const cell = tableGrid[position.y]
  4. ? tableGrid[position.y][position.x]
  5. : undefined;
  6. if (!cell) {
  7. return [];
  8. }
  9. if (typeof callback === 'function') {
  10. result = callback(cell, position, tableGrid);
  11. if (result === true) {
  12. // abort
  13. return [cell];
  14. }
  15. }
  16. result = traverseTable(
  17. dir,
  18. {
  19. x: position.x + dir.x,
  20. y: position.y + dir.y
  21. },
  22. tableGrid,
  23. callback
  24. );
  25. result.unshift(cell);
  26. return result;
  27. }
  28. /**
  29. * Traverses a table in a given direction, passing the cell to the callback
  30. * @method traverse
  31. * @memberof axe.commons.table
  32. * @instance
  33. * @param {Object|String} dir Direction that will be added recursively {x: 1, y: 0}, 'left';
  34. * @param {Object} startPos x/y coordinate: {x: 0, y: 0};
  35. * @param {Array} [tablegrid] A matrix of the table obtained using axe.commons.table.toArray (OPTIONAL)
  36. * @param {Function} callback Function to which each cell will be passed
  37. * @return {NodeElement} If the callback returns true, the traversal will end and the cell will be returned
  38. */
  39. function traverse(dir, startPos, tableGrid, callback) {
  40. if (Array.isArray(startPos)) {
  41. callback = tableGrid;
  42. tableGrid = startPos;
  43. startPos = { x: 0, y: 0 };
  44. }
  45. if (typeof dir === 'string') {
  46. switch (dir) {
  47. case 'left':
  48. dir = { x: -1, y: 0 };
  49. break;
  50. case 'up':
  51. dir = { x: 0, y: -1 };
  52. break;
  53. case 'right':
  54. dir = { x: 1, y: 0 };
  55. break;
  56. case 'down':
  57. dir = { x: 0, y: 1 };
  58. break;
  59. }
  60. }
  61. return traverseTable(
  62. dir,
  63. {
  64. x: startPos.x + dir.x,
  65. y: startPos.y + dir.y
  66. },
  67. tableGrid,
  68. callback
  69. );
  70. }
  71. export default traverse;