-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrouper.js
62 lines (52 loc) · 1.51 KB
/
grouper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
returns a chunk of text
*/
function grouper(
items, // array of items to iterate over
render, // function to render each line - returns an array which must have an odd number of elements
counter // bool, wether we inject counter data into the item
) {
var arraySize = -1,
html = '',
item, c, d, last,
current, halfSize,
lastMatchDepth, matchDepth;
// first find the size of the array returned
if (!items){
return '';
}
current = render(items[0]);
arraySize = current.length;
halfSize = (arraySize + 1) / 2;
lastMatchDepth = 1;
matchDepth = halfSize;
for (c=0; c<items.length;c++) {
item = items[c];
current = render(item);
// how deep does it match the last row?
// if it doesn't match in same way, close the previous bits of the last row
if (last) {
matchDepth = 0;
for (d = 0; d <= halfSize; d++) {
if (last[d] === current[d]) {
matchDepth++;
}
}
}
if (matchDepth > halfSize){
//html += '!! '+matchDepth + ' , '+lastMatchDepth;
//html += current.slice(lastMatchDepth - 1, matchDepth).join('');
matchDepth = halfSize;
} else if (last && matchDepth < lastMatchDepth) {
html += last.slice(arraySize - lastMatchDepth+1, arraySize - matchDepth + 1).join('');
html += current.slice(matchDepth - 1, halfSize).join('');
matchDepth = halfSize;
} else {
html += current.slice(lastMatchDepth - 1, matchDepth).join('');
}
last = current;
lastMatchDepth = matchDepth;
}
html += current.slice(matchDepth, arraySize).join('');
return html;
}