I have a inherited a system that utilizes a Backbone collection of files that needs to be sorted based on a series of values. The order variable is saved when you slide different files into a position in the view. It mostly works but there are rare times when it is not sorted correctly based on values in the files_order list. I found that using the unsigned right shift came the closest to working but the code is returning odd results as a number of the files in the collection are not in the files_order.
For filecollectionid = 1, the system result is:
36528,36524,36529,35526,36523,36525,36530,36531
The correct order should be:
36528,36523,36524,36525,35526,36529,36530,36531
I am assuming the unsigned right shift of variables that do not exist in the list are causing the problem. Any help would be greatly appreciated.
collection = new Backbone.Collection([
{ id: 36523, name: "File 1", filecollectionid: 1 },
{ id: 36524, name: "File 2", filecollectionid: 1 },
{ id: 36525, name: "File 3", filecollectionid: 1 },
{ id: 36526, name: "File 4", filecollectionid: 1 },
{ id: 36528, name: "File 5", filecollectionid: 1 },
{ id: 36529, name: "File 6", filecollectionid: 1 },
{ id: 36530, name: "File 7", filecollectionid: 1 },
{ id: 36531, name: "File 8", filecollectionid: 1 },
{ id: 36476, name: "Video 1", filecollectionid: 6 },
{ id: 36520, name: "Video 2", filecollectionid: 6 },
{ id: 36527, name: "Video 3", filecollectionid: 6 }
]);
sections = {
"id": 1,
"files_order" : [36503,36513,36505,36506,36507,36508,36509,36510,36511,36521,36528,36522,35523,36524]
}
collection.sort(function(a,b) {
// Lets group files by the file collection id first
if(a.filecollectionid != b.filecollectionid){
return a.filecollectionid - b.filecollectionid;
}
// Lets try to use the files_order variable
try {
// Get the files_order field
var files_order = _.find(sections, function(section) {
// They should both have the same filecollectionid
return a.filecollectionid == section.id;
}).files_order;
files_order = _.map(JSON.parse(files_order.toString()), function(item) {
return parseInt(item);
});
// use unsigned right shift to keep the original and add the unadded to the end
return (files_order.indexOf(a.id) >>> 0) - (files_order.indexOf(b.id) >>> 0);
} catch(e) {
// If no sorting order this really should be oldest first and newest last.
a = a.id;
b = b.id;
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}
});