Skip to content

Instantly share code, notes, and snippets.

@bitifet
Created October 13, 2014 00:08
Show Gist options
  • Save bitifet/9861b0a30b10a51e5f4e to your computer and use it in GitHub Desktop.
Save bitifet/9861b0a30b10a51e5f4e to your computer and use it in GitHub Desktop.
Array with steroids.
"use strict"
var myArray = (function(Array) { // Array with steroids.//{{{
// Implement an Array clone with extended functions.
// In only imlements a simple .contains() method, but can be extended to
// add many more.
// The main key feature is the ability to do this WITHOUT
// altering the original Array object in any way.
// NOTE: Now we should use the myArray object to declare it. Main goal
// is to implement it as "var Array = (function(arr){...})(Array);"
// This way we will achieve a "local" context-related Array replacement
// without affecting any other part (specially third party librarys) of our
// project.
//
// ...but I did'nt got it for now...
function searchInArray(){ // .contains() implementation.//{{{
for(var j in this){
if(this[j]==arguments[0]){
return true;
}
}
return false;
};//}}}
var myArr = function() { // Our Array replacement.//{{{
var arr = Array.apply(this, arguments);
Object.defineProperty (
arr,
"contains",
{
value: searchInArray,
writable: true,
configurable: true,
enumerable: false
}
);
return arr;
};//}}}
myArr.prototype = Array.prototype; // Preserve original Array .prototype
return myArr;
})(Array);//}}}
// Some testing...
console.log ("new myArray('a', 'b').contains('y'));");
var b = new myArray('a', 'b').contains('y');
console.log ('Type:', typeof b);
console.log ('Value:', b);
var x = new myArray(1, 2, 3);
console.log ("-------------------------");
console.log ('Contents:', x);
console.log ('Length:', x.length);
console.log ('typeof x.contains:', typeof x.contains);
console.log ('x.contains(2):', x.contains(2));
console.log ("-------------------------");
console.log ('Enumerable propertys (array walking):');
for (var i in x) { console.log (i, x[i]);};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment