0
我已经实现了将重叠现有范围划分为日期/数字范围列表的算法。分割重叠范围
该算法正在工作,但我想知道如果你可以避免算法的最后一个循环。
有可能吗?
0-100(红) 90-150(绿色) 90-150(蓝色) 140-300(黄色) 170-240(黑色) 350-530(橙色) 50-500(银) 50-60(粉红色)
0-49(红色) 50-60(红色,银色,粉色) 61-89(红色,银色)01 (绿色,蓝色,银色) 140-150(绿色,蓝色,黄色,银色) (黄,黑,银) 241-300(黄色,银) 301-349(银) 350-500(橙色,银色) 501-530(橙色)
JavaScript代码:
function splitRanges(original_intervals) {
for (var to = [], from = [], n, i = original_intervals.length; i--;) {
if (to.indexOf(n = original_intervals[i].to) < 0)
to.push(n);
if (from.indexOf(n = original_intervals[i].from) < 0)
from.push(n);
}
to.sort(function(a, b) {
return a - b;
});
from.sort(function(a, b) {
return a - b;
});
var intervals = [];
while (to.length) {
var sFrom = from.shift();
var sTo = 0;
if (from.length == 0) {
sTo = (from.push((n = to.shift()) + 1), n);
} else {
if (from[0] > to[0]) {
while (to[0] < from[0]) {
from.unshift(to[0] + 1);
to.shift();
}
sTo = from[0] - 1;
} else {
sTo = from[0] - 1;
}
}
intervals.push({
from: sFrom,
to: sTo,
colors: []
});
}
/***********************Loop that i want remove*/
intervals.forEach(function(item, index) {
original_intervals.forEach(function(item1, index1) {
if ((item.from >= item1.from && item.from <= item1.to) || (item.to >= item1.from && item.to <= item1.to))
item.colors.push(item1.color);
});
});
return intervals;
}
var r1 = [{
id: 1,
from: 0,
to: 100,
\t color:'red'
}, {
id: 2,
from: 90,
to: 150,
\t color:'green'
}, {
id: 3,
from: 90,
to: 150,
\t color:'blue'
}, {
id: 4,
from: 140,
to: 300,
\t color:'yellow'
}, {
id: 5,
from: 170,
to: 240,
\t color:'black'
}, {
id: 6,
from: 350,
to: 530,
\t color:'orange'
}, {
id: 7,
from: 50,
to: 500,
\t color:'silver'
}
, {
id: 8,
from: 50,
to: 60,
\t color:'pink'
}
];
console.log(splitRanges(r1));
请提供文本形式的数据。 –