Skip to content

Instantly share code, notes, and snippets.

@furkanmustafa
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furkanmustafa/9533398 to your computer and use it in GitHub Desktop.
Save furkanmustafa/9533398 to your computer and use it in GitHub Desktop.
Simple routines for ordering database data in javascript
var collectionOrder = function(options) {
this.itemCount = options.itemCount;
this.move = options.move;
this.fetch = options.fetch;
if (typeof options.batchMove !== "undefined") {
this.batchMove = options.batchMove;
} else {
this.batchMove = this._batchMoveInternal;
}
};
collectionOrder.prototype.moveItemToIndex = function(fromIndex, toIndex) {
var item = this.fetch(fromIndex);
if (toIndex > fromIndex) {
this.batchMove(fromIndex + 1, toIndex - fromIndex, -1);
} else {
this.batchMove(toIndex, fromIndex - toIndex, 1);
}
this.move(item, toIndex);
};
collectionOrder.prototype._batchMoveInternal = function(fromIndex, length, movement) {
if (movement == -1) {
for (i = 0; i < length; i++) {
var iItem = this.fetch(i + fromIndex);
this.move(iItem, i + fromIndex + movement);
}
} else {
for (i = length - 1; i >= 0; i--) {
var iItem = this.fetch(i + fromIndex);
this.move(iItem, i + fromIndex + movement);
}
}
}
// example code
var items = [
'ali', 'veli', 'deli', 'kirk', 'dokuz', 'elli'
];
var order = new collectionOrder({
itemCount: items.length,
move: function(item, toIndex) {
console.log("\tMoving Item '" + item + "' to " + toIndex);
var hold = null;
if (items[toIndex]) {
hold = items[toIndex];
}
items[toIndex] = item;
return hold;
},
fetch: function(itemIndex) {
console.log("Fetching Item [" + itemIndex + "] : '" + items[itemIndex] + "'");
return items[itemIndex];
}
});
order.moveItemToIndex(0, 5);
console.log(items);
// mongoose example (not tested)
var query = { category_id: 5 }; // ex: ordering items in a category
MyObjectModel.find(query, '_id order', { sort: { order: 1 } }, function (err, docs) {
var order = new collectionOrder({
itemCount: docs.length,
move: function(item, toIndex) {
item.order = toIndex;
item.save();
},
fetch: function(index) {
return _.findWhere(docs, { // underscore.js
"order": index
});
},
batchMove: function(fromIndex, length, movement) { // this is optional. to reduce queries.
var updateQuery = query;
updateQuery.order = { $gte: fromIndex, $lt: fromIndex + length };
MyObjectModel.update(updateQuery, { $inc: { order: movement } } );
}
});
order.moveItemToIndex(3, 15); // pops theItem at index 3, shifts 4..15 to left, and puts theItem into index:15.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment