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));
請提供文本形式的數據。 –