Skip to content

Instantly share code, notes, and snippets.

@katowulf
Created June 10, 2016 18:25
Show Gist options
  • Save katowulf/e924b78aaf8584f5c8a2387b19b3697f to your computer and use it in GitHub Desktop.
Save katowulf/e924b78aaf8584f5c8a2387b19b3697f to your computer and use it in GitHub Desktop.
Descending sorted array in AngularFire, accomplished by unshift() instead of push().
app.factory('DescendingArray', function($firebaseArray) {
return $firebaseArray.$extend({
// Modify $$process to handle added events by prepending instead of appending
$$process: function(event, rec, prevChild) {
var key = this.$$getKey(rec);
var changed = false;
if( event === 'child_added' ) {
curPos = this.$indexFor(key);
changed = this._addBefore(rec, prevChild) !== curPos;
if( changed ) {
// send notifications to anybody monitoring $watch
//todo maybe prevChild here should be the record before?
//todo we could fetch this with $indexFor(key)-1?
this.$$notify(event, key, prevChild);
}
return changed;
}
else {
return $firebaseArray.prototype.$$process.apply(this, arguments);
}
},
/**
* Used to insert new records in descending order instead or normal ascending order
*
* @param {object} rec
* @param {string|null} prevChild
* @private
*/
_addBefore: function(rec, prevChild) {
var i;
if( prevChild === null ) {
i = this.$list.length;
}
else {
i = this.$indexFor(prevChild);
if( i === -1 ) { i = 0; }
}
this.$list.splice(i, 0, rec);
this._indexCache[this.$$getKey(rec)] = i;
return i;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment