"Crowds are not always wise"
— Dr. Xavier Amatriain “Improving recommendations”
While I was porting a JavaScript class from the client side to the server side, I’ve found a nice utility from NodeJS to simplify the inheritance patterns on JavaScript. You all know there’s a few cool methods and techniques floating around, here a few nice articles about that:
Classical Inheritance in JavaScript,
Simple JavaScript Inheritance and
Inheritance revisited. Well, the thing is, with NodeJS, things get simpler.
Let’s say you have a List class you want to inherit from, to create a ComplexList class, with NodeJS you can use
util.inherits method to simplify the pattern and avoid doing monkey business.
Example:
var List = function(arr) {
this.children = arr;
}
List.prototype.ordered = true;
List.prototype.sort = function() { ... }
var ComplexList = function(arr) {
/** @borrow List.constructor */
List.call(this, arr);
}
/** @inheritance */
util.inherits(ComplexList, List);
ComplexList.prototype.complexProperty = true;
ComplexList.prototype.complexSorting = function() { ... }
var Players = new ComplexList();
Players.sort(); // inherit from List
console.log(Players instanceof ComplexList) // true
console.log(Players instanceof List) // true
It’s that simple. Hope you find this useful!
Update: There’s some discussion on the NodeJS mailing list about deprecating util.inherits, so be aware of it on the next versions. I’ll be using it anyway
I came across this simple solution, to sort collections with JavaScript by datetime and I think it worth to share it. I would prefer to sort and filter collections on the server side, but some times, we need to tweak things and we can’t change APIs right away. So here a quick fix to do it with JavaScript.
// Let's say you have a date collection of things, like:
var collection = [
{name: '#1 thing', time: '2012-03-16T07:22Z'},
{name: '#2 thing', time: '2012-03-15T12:00Z'},
{name: '#3 thing', time: '2012-03-17T20:25Z'},
{name: '#4 thing', time: '2012-03-13T13:45Z'}
];
// the sorting function
var sortFunction = function(a, b) {
// check this docs page from mozilla
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
// we use date objects to get milliseconds values
return new Date(a.time).valueOf() - new Date(b.time).valueOf();
}
// Apply the sort function
collection.sort(sortFunction);
// See te results
console.log(collection);
I hope you find this tip useful!