Sha256: 06e4d0037715251cb3be2b2db063662f555b3538d9e30a9c517a54374d941cbc

Contents?: true

Size: 1.19 KB

Versions: 74

Compression:

Stored size: 1.19 KB

Contents

'use strict';
module.exports = balanced;
function balanced(a, b, str) {
  if (a instanceof RegExp) a = maybeMatch(a, str);
  if (b instanceof RegExp) b = maybeMatch(b, str);

  var r = range(a, b, str);

  return r && {
    start: r[0],
    end: r[1],
    pre: str.slice(0, r[0]),
    body: str.slice(r[0] + a.length, r[1]),
    post: str.slice(r[1] + b.length)
  };
}

function maybeMatch(reg, str) {
  var m = str.match(reg);
  return m ? m[0] : null;
}

balanced.range = range;
function range(a, b, str) {
  var begs, beg, left, right, result;
  var ai = str.indexOf(a);
  var bi = str.indexOf(b, ai + 1);
  var i = ai;

  if (ai >= 0 && bi > 0) {
    if(a===b) {
      return [ai, bi];
    }
    begs = [];
    left = str.length;

    while (i >= 0 && !result) {
      if (i == ai) {
        begs.push(i);
        ai = str.indexOf(a, i + 1);
      } else if (begs.length == 1) {
        result = [ begs.pop(), bi ];
      } else {
        beg = begs.pop();
        if (beg < left) {
          left = beg;
          right = bi;
        }

        bi = str.indexOf(b, i + 1);
      }

      i = ai < bi && ai >= 0 ? ai : bi;
    }

    if (begs.length) {
      result = [ left, right ];
    }
  }

  return result;
}

Version data entries

74 entries across 74 versions & 8 rubygems

Version Path
trusty-cms-6.3.1 node_modules/brace-expansion/node_modules/balanced-match/index.js
immosquare-cleaner-0.1.51 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.50 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.49 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.48 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.47 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.46 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.45 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.44 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.43 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.42 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.41 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.40 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.39 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.38 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.32 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.31 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.30 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.29 node_modules/balanced-match/index.js
immosquare-cleaner-0.1.28 node_modules/balanced-match/index.js