J'ai implémenté un algorithme pour diviser les plages existantes qui se chevauchent en une liste de plages de dates/numéros.Diviser les plages de chevauchement
L'algorithme fonctionne mais je me demandais si vous pouviez éviter la dernière boucle de l'algorithme.
C'est possible?
0-100 (rouge) 90-150 (vert) 90-150 (bleu) 140-300 (jaune) 170-240 (noir) 350-530 (orange) 50-500 (argent) 50-60 (rose)
0-49 (rouge) 50-60 (rouge, argent, rose) 61-89 (rouge, argent) 90-100 (rouge, vert, bleu, argent) 101-139 (vert, bleu, argent) 140-150 (vert, bleu, jaune, argent) 151-169 (jaune, argent) 170-240 (jaune, noir, argent) 241-300 (jaune, argent) 301-349 (argent) 350-500 (orange, argent) 501-530 (orange)
code 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));
s'il vous plaît fournir les données sous forme de texte. –