Skip to content

Instantly share code, notes, and snippets.

@KhodeN
Created November 21, 2014 03:45
Show Gist options
  • Save KhodeN/f5dbd4793be88cf6b22a to your computer and use it in GitHub Desktop.
Save KhodeN/f5dbd4793be88cf6b22a to your computer and use it in GitHub Desktop.
getBoundsWithBreaks
function getBoundsWithBreaks (text, subString) {
var breaks = [];
_.forEach(text, function (char, index) {
if (char === '\n') {
breaks.push(index);
}
});
var startIndex = text.replace(/\n/g, '').indexOf(subString);
if (startIndex === -1) {
return;
}
var breaksBefore = _.filter(breaks, function (pos, index) {
return pos < startIndex + index;
});
// начало - позиция плюс кол-во новых строк до этой позиции
var start = startIndex + breaksBefore.length;
// текущий фрагмент
var fragment = subString;
_.forEach(breaks, function (pos) {
if (pos > start && pos < fragment.length + start) {
fragment = fragment.slice(0, pos - start) + '\n' + fragment.slice(pos - start);
}
});
var end = start + fragment.length;
return {
start: start,
end: end,
fragment: fragment
};
}
it('getBounds', function () {
var result;
result = getBoundsWithBreaks('Приговор приведён в исполнение', 'говор прив');
expect(result.start).toBe(3);
expect(result.end).toBe(13);
expect(result.fragment).toBe('говор прив');
result = getBoundsWithBreaks('Приговор\n при\n\nведён в исполнение', 'говор прив');
expect(result.start).toBe(3);
expect(result.end).toBe(16);
expect(result.fragment).toBe('говор\n при\n\nв');
result = getBoundsWithBreaks('1 2 3 4 45', '3 4');
expect(result.start).toBe(4);
expect(result.end).toBe(7);
expect(result.fragment).toBe('3 4');
result = getBoundsWithBreaks('should return promise with response body', 'promise with');
expect(result.start).toBe(14);
expect(result.end).toBe(26);
expect(result.fragment).toBe('promise with');
result = getBoundsWithBreaks('should\n return promise\n with response body', 'promise with');
expect(result.start).toBe(15);
expect(result.end).toBe(28);
expect(result.fragment).toBe('promise\n with');
// TODO граничные условия
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment