Home > Back-end >  Monkey patching Array in JavaScript for unique function return?
Monkey patching Array in JavaScript for unique function return?

Time:07-20

I am do not have a degree and will be on welfare until I get a job as a software engineer as a self taught programmer; You can effectively say I am dead and I do not consider my self to be a living human being. I am trying to monkey patch the Array function to create a uniq() function that returns an array of all elements unique to the Array. Below is my code:

Array.proptype.uniq = function() {
    narr = [];
    this.forEach(element => {
        if (!narr.includes(element)) {
            narr.push(element);
        };
    });
    return narr;
};
console.log([1,1,1,4,5,5,6,7,8,9,9,9,9,10,11,13,13,14,14,15,15,16,16,17,17,17,18,18].uniq());

I simply get 'undefined'. Why is this happening and what basic concept do I not know? I get the error:

[noah@Qyain intro]$ node phase_1_arrays.js
/home/noah/intro/phase_1_arrays.js:1
Array.proptype.uniq = function() {
                    ^

TypeError: Cannot set properties of undefined (setting 'uniq')
    at Object.<anonymous> (/home/noah/intro/phase_1_arrays.js:1:21)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Also the array is returned either empty or with the 1 in it so the forEach does not execute. I know this has something to do with syntax and not my logic I believe.

CodePudding user response:

If you define a function as

Array.uniq = ...

then you need to call it as

Array.uniq([...]).

If you want to call it like you do, you need to add it to the prototype:

Array.prototype.uniq = ....

Then you can do

[...].uniq()

So, as a result, your code could look e.g. like this:

Array.prototype.uniq = function (){
    narr = [];
    this.forEach(element => {
        if (!narr.includes(element)) {
            narr.push(element);
        };
    });
    return narr;
};

and you can call it like this:

console.log([1,1,1,4,5,5,6,7,8,9,9,9,9,10,11,13,13,14,14,15,15,16,16,17,17,17,18,18].uniq());
> [1, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18]

Is this what you need?

  • Related