11cb0ef41Sopenharmony_ci'use strict'; 21cb0ef41Sopenharmony_cimodule.exports = balanced; 31cb0ef41Sopenharmony_cifunction balanced(a, b, str) { 41cb0ef41Sopenharmony_ci if (a instanceof RegExp) a = maybeMatch(a, str); 51cb0ef41Sopenharmony_ci if (b instanceof RegExp) b = maybeMatch(b, str); 61cb0ef41Sopenharmony_ci 71cb0ef41Sopenharmony_ci var r = range(a, b, str); 81cb0ef41Sopenharmony_ci 91cb0ef41Sopenharmony_ci return r && { 101cb0ef41Sopenharmony_ci start: r[0], 111cb0ef41Sopenharmony_ci end: r[1], 121cb0ef41Sopenharmony_ci pre: str.slice(0, r[0]), 131cb0ef41Sopenharmony_ci body: str.slice(r[0] + a.length, r[1]), 141cb0ef41Sopenharmony_ci post: str.slice(r[1] + b.length) 151cb0ef41Sopenharmony_ci }; 161cb0ef41Sopenharmony_ci} 171cb0ef41Sopenharmony_ci 181cb0ef41Sopenharmony_cifunction maybeMatch(reg, str) { 191cb0ef41Sopenharmony_ci var m = str.match(reg); 201cb0ef41Sopenharmony_ci return m ? m[0] : null; 211cb0ef41Sopenharmony_ci} 221cb0ef41Sopenharmony_ci 231cb0ef41Sopenharmony_cibalanced.range = range; 241cb0ef41Sopenharmony_cifunction range(a, b, str) { 251cb0ef41Sopenharmony_ci var begs, beg, left, right, result; 261cb0ef41Sopenharmony_ci var ai = str.indexOf(a); 271cb0ef41Sopenharmony_ci var bi = str.indexOf(b, ai + 1); 281cb0ef41Sopenharmony_ci var i = ai; 291cb0ef41Sopenharmony_ci 301cb0ef41Sopenharmony_ci if (ai >= 0 && bi > 0) { 311cb0ef41Sopenharmony_ci if(a===b) { 321cb0ef41Sopenharmony_ci return [ai, bi]; 331cb0ef41Sopenharmony_ci } 341cb0ef41Sopenharmony_ci begs = []; 351cb0ef41Sopenharmony_ci left = str.length; 361cb0ef41Sopenharmony_ci 371cb0ef41Sopenharmony_ci while (i >= 0 && !result) { 381cb0ef41Sopenharmony_ci if (i == ai) { 391cb0ef41Sopenharmony_ci begs.push(i); 401cb0ef41Sopenharmony_ci ai = str.indexOf(a, i + 1); 411cb0ef41Sopenharmony_ci } else if (begs.length == 1) { 421cb0ef41Sopenharmony_ci result = [ begs.pop(), bi ]; 431cb0ef41Sopenharmony_ci } else { 441cb0ef41Sopenharmony_ci beg = begs.pop(); 451cb0ef41Sopenharmony_ci if (beg < left) { 461cb0ef41Sopenharmony_ci left = beg; 471cb0ef41Sopenharmony_ci right = bi; 481cb0ef41Sopenharmony_ci } 491cb0ef41Sopenharmony_ci 501cb0ef41Sopenharmony_ci bi = str.indexOf(b, i + 1); 511cb0ef41Sopenharmony_ci } 521cb0ef41Sopenharmony_ci 531cb0ef41Sopenharmony_ci i = ai < bi && ai >= 0 ? ai : bi; 541cb0ef41Sopenharmony_ci } 551cb0ef41Sopenharmony_ci 561cb0ef41Sopenharmony_ci if (begs.length) { 571cb0ef41Sopenharmony_ci result = [ left, right ]; 581cb0ef41Sopenharmony_ci } 591cb0ef41Sopenharmony_ci } 601cb0ef41Sopenharmony_ci 611cb0ef41Sopenharmony_ci return result; 621cb0ef41Sopenharmony_ci} 63