Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. 'use strict';
  2. module.exports = balanced;
  3. function balanced(a, b, str) {
  4. if (a instanceof RegExp) a = maybeMatch(a, str);
  5. if (b instanceof RegExp) b = maybeMatch(b, str);
  6. var r = range(a, b, str);
  7. return r && {
  8. start: r[0],
  9. end: r[1],
  10. pre: str.slice(0, r[0]),
  11. body: str.slice(r[0] + a.length, r[1]),
  12. post: str.slice(r[1] + b.length)
  13. };
  14. }
  15. function maybeMatch(reg, str) {
  16. var m = str.match(reg);
  17. return m ? m[0] : null;
  18. }
  19. balanced.range = range;
  20. function range(a, b, str) {
  21. var begs, beg, left, right, result;
  22. var ai = str.indexOf(a);
  23. var bi = str.indexOf(b, ai + 1);
  24. var i = ai;
  25. if (ai >= 0 && bi > 0) {
  26. begs = [];
  27. left = str.length;
  28. while (i >= 0 && !result) {
  29. if (i == ai) {
  30. begs.push(i);
  31. ai = str.indexOf(a, i + 1);
  32. } else if (begs.length == 1) {
  33. result = [ begs.pop(), bi ];
  34. } else {
  35. beg = begs.pop();
  36. if (beg < left) {
  37. left = beg;
  38. right = bi;
  39. }
  40. bi = str.indexOf(b, i + 1);
  41. }
  42. i = ai < bi && ai >= 0 ? ai : bi;
  43. }
  44. if (begs.length) {
  45. result = [ left, right ];
  46. }
  47. }
  48. return result;
  49. }