Path: blob/master/node_modules/balanced-match/index.js
1126 views
'use strict';1module.exports = balanced;2function balanced(a, b, str) {3if (a instanceof RegExp) a = maybeMatch(a, str);4if (b instanceof RegExp) b = maybeMatch(b, str);56var r = range(a, b, str);78return r && {9start: r[0],10end: r[1],11pre: str.slice(0, r[0]),12body: str.slice(r[0] + a.length, r[1]),13post: str.slice(r[1] + b.length)14};15}1617function maybeMatch(reg, str) {18var m = str.match(reg);19return m ? m[0] : null;20}2122balanced.range = range;23function range(a, b, str) {24var begs, beg, left, right, result;25var ai = str.indexOf(a);26var bi = str.indexOf(b, ai + 1);27var i = ai;2829if (ai >= 0 && bi > 0) {30if(a===b) {31return [ai, bi];32}33begs = [];34left = str.length;3536while (i >= 0 && !result) {37if (i == ai) {38begs.push(i);39ai = str.indexOf(a, i + 1);40} else if (begs.length == 1) {41result = [ begs.pop(), bi ];42} else {43beg = begs.pop();44if (beg < left) {45left = beg;46right = bi;47}4849bi = str.indexOf(b, i + 1);50}5152i = ai < bi && ai >= 0 ? ai : bi;53}5455if (begs.length) {56result = [ left, right ];57}58}5960return result;61}626364