JSFiddle - React, Tailwind, and code Playground
by hamix
JavaScript
// Define the collection class.
window.Collection = (function(){
// I am the constructor function.
function Collection(){
// When creating the collection, we are going to work off
// the core array. In order to maintain all of the native
// array features, we need to build off a native array.
var collection = Object.create( Array.prototype );
// Initialize the array. This line is more complicated than
// it needs to be, but I'm trying to keep the approach
// generic for learning purposes.
collection = (Array.apply( collection, arguments ) || collection);
// Add all the class methods to the collection.
Collection.injectClassMethods( collection );
// Return the new collection object.
return( collection );
}
// ------------------------------------------------------ //
// ------------------------------------------------------ //
// Define the static methods.
Collection.injectClassMethods = function( collection ){
// Loop over all the prototype methods and add them
// to the new collection.
for (var method in Collection.prototype){
// Make sure this is a local method.
if (Collection.prototype.hasOwnProperty( method )){
// Add the method to the collection.
collection[ method ] = Collection.prototype[ method ];
}
}
// Return the updated collection.
return( collection );
};
// I create a new collection from the given array.
Collection.fromArray = function( array ){
// Create a new collection.
var collection = Collection.apply( null, array );
// Return the new collection.
return( collection );
};
// I determine if the given object is an array.
Collection.isArray = function( value ){
// Get it's stringified version.
var stringValue = Object.prototype.toString.call( value );
// Check to see if the string represtnation denotes array.
return( stringValue.toLowerCase() === "[object array]" );
};
// ------------------------------------------------------ //
// ------------------------------------------------------ //
...