strind
Version:
Partition strings based on character indices
57 lines (56 loc) • 1.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Partitions a string based on character indices.
*
* @param {string} str - string to partition
* @param {[number,number][]} indices - array of tuples to match [start, end] indices
* @param {function} callback - callback function called with matching characters
*/
function strind(str, indices, callback) {
var strs = str.split('');
var strsLen = strs.length;
var idx = Array.isArray(indices[0]) ? indices : [indices];
var partition = [];
var nonmatched = [];
function updateNonmatched(open, close, index) {
var chars = str.slice(open, close);
if (!chars.length) {
return;
}
nonmatched.push({ chars: chars, index: index });
if (callback) {
var cb = callback({ chars: chars, matches: false });
partition.push(cb);
}
}
for (var i = 0, len = idx.length; i < len; i++) {
var _a = idx[i], start = _a[0], end = _a[1];
var floor = start >= 0 ? start : 0;
var ceiling = end >= strsLen ? strsLen : end + 1;
if (i === 0 && start > 0) {
updateNonmatched(0, start, 0);
}
var chars = str.slice(floor, ceiling);
if (callback) {
var cb = callback({ chars: chars, matches: true });
partition.push(cb);
}
else {
partition.push(chars);
}
if (end < strsLen) {
var open = end + 1;
var close = i < len - 1 ? idx[i + 1][0] : strsLen;
updateNonmatched(open, close, partition.length);
}
if (end >= strsLen) {
break;
}
}
return {
unmatched: nonmatched,
matched: partition
};
}
exports.default = strind;