Adding Custom Functions into Array.Prototype

adding custom functions into Array.prototype

While the potential for clashing with other bits o' code the override a function on a prototype is still a risk, if you want to do this with modern versions of JavaScript, you can use the Object.defineProperty method, e.g.

// functional sort
Object.defineProperty(Array.prototype, 'sortf', {
value: function(compare) { return [].concat(this).sort(compare); }
});

Run custom method on array update/create in JavaScript

I don't think you can "hijack" all arrays just like that. Even if you monkey patch the native Array function, arrays created with the literal notation i.e. [] won't be affected by that:

console.log(new Array(1,2,3));
console.log([4,5,6]);

Array = function () {
throw new Error;
};

try {
console.log(new Array(1,2,3));
} catch (e) {
console.log('Cannot create array with new Array');
}

console.log([4,5,6]);

Adding Methods to array prototype so i can apply it to array object.But it is giving an error TypeError: Array.method is not a function

Most of the code you have tried is correct. I think you are trying to add all the elements and return using reduce function to array. But to achieve what you wanted,checkout fiddle link:

http://jsfiddle.net/x2ydm091/2/

Array.prototype.reduce=function(f, value){
for(var i=0;i< this.length;i++){
value=f(this[i],value);
}
return value;
};

var add = function(a,b){
return a+b;
}

var data = [1,3,2,4,5,6,7,8,9];
var result = data.reduce(add,0);
alert(result);

Hope that helps!

Adding custom function to object prototype

By using arrow function you can't bind "this" so in the context of the prototype this equals to "window".

Try this:

Array.prototype.get = function(index){
return this[index];
};

Best practice when adding custom method to Array (Built-in object)

Extending built-in prototypes has always triggered debates, and I think we can conclude it is not considered best practice.

On the other hand it is indeed nice if you can call these custom methods as object methods instead of plain functions.

You might consider a wrapper function that will return an Array instance that has the extra methods defined for it: i.e., not on the prototype, but on the Array instance itself.

Your module could look like this:

function iArray(arr) {
return Object.assign([], arr || [], {
iSlice: iSliceBuiltin,
iSplice: iSpliceBuiltin
});
}

// ... your module functions come here, but excluding the changes to the Array prototype

module.exports = {
iArray
}

Then you would use it like this:

const iArray = require('inverted-slice');

let arr1 = iArray([1,2,3,4]); // enrich array with extra methods
let result = arr1.iSlice(0, 1);

To allow chaining, you could change the return statement in iSliceSpliceHelper to:

return iArray(newArr);

So, now you can write:

let arr1 = iArray([1,2,3,4]); // enrich array with extra methods
let result = arr1.iSlice(0, 1).iSlice(1, 2);

Existing libraries might implement your alternative 1 (e.g. underscore), but many also go for something like I propose here. See for instance Sugar (new Sugar.Array([1,2,3])), or Lazy (Lazy([1,2,3])).

JavaScript: Best way to add custom properties/methods to built-in objects (e.g. arrays)

Method 1 and Method 3 do the same thing. You're just defining functions against an instantiated array. If you're after speed simply stick with methods 1 or 3. Turns out classes extended from array and prototypes from arrays (which is the same thing under the hood) are simply very slow when it comes to large volumes of data. Small cases it's probably fine. I can't seem to find much info on this subject myself either. But hopefully this is a good starting point for further testing. It could take 10ish seconds to complete the test so be patient...

//Method 1
let myArray1 = [];
myArray1.unique = () => [...new Set(myArray1)];
myArray1.last = () => myArray1.at(-1);
//Method 2
class superArray extends Array {
constructor(...items) { super(...items) }
unique(){return [...new Set(this)]}
last(){ return this.at(-1)}
}
let myArray2 = new superArray();
//Method 3
let superArrayMethods = {
unique: function(){return [...new Set(this)]},
last: function(){return this.at(-1)}
}
let myArray3 = [];
myArray3 = Object.assign(myArray3, superArrayMethods);
//Method 4
let superArrayPrototype = {
unique: function(){return [...new Set(this)]},
last: function(){return this.at(-1)}
}
Object.setPrototypeOf(superArrayPrototype,Array.prototype);
let myArray4 = [];
Object.setPrototypeOf(myArray4,superArrayPrototype);

//Timers
console.time("myArray1")
for(i=0; i<10000000; i++) { myArray1.push(i); }
console.timeEnd("myArray1")

console.time("myArray2")
for(i=0; i<10000000; i++) { myArray2.push(i); }
console.timeEnd("myArray2")

console.time("myArray3")
for(i=0; i<10000000; i++) { myArray3.push(i); }
console.timeEnd("myArray3")

console.time("myArray4")
for(i=0; i<10000000; i++) { myArray4.push(i); }
console.timeEnd("myArray4")

console.time("unique myArray1")
myArray1.unique();
console.timeEnd("unique myArray1")

console.time("unique myArray2")
myArray2.unique();
console.timeEnd("unique myArray2")

console.time("unique myArray3")
myArray3.unique();
console.timeEnd("unique myArray3")

console.time("unique myArray4")
myArray4.unique();
console.timeEnd("unique myArray4")


Related Topics



Leave a reply



Submit