Home > Software engineering >  Unable to monkey patch array using uniq in JS [beginner]
Unable to monkey patch array using uniq in JS [beginner]

Time:05-02

Array.prototype.uniq = function() {
  narr = [];
  for (let i = 0; i < 0; i  ) {
    if (!narr.include(this[i])) {
      narr.push(this[i]);
    }
  }
  return narr;
}

console.log(([1, 2, 2, 3, 3, 3].uniq() => [1, 2, 3]));

I am trying to monkey patch the above code but I receive:

/home/cameronnc/Documents/app/skeleton/phase_1_arrays.js:11 console.log(([1,2,2,3,3,3].uniq() => [1,2,3])); ^^^^^

SyntaxError: Malformed arrow function parameter list at Object.compileFunction (node:vm:352:18) at wrapSafe (node:internal/modules/cjs/loader:1033:15) at Module._compile (node:internal/modules/cjs/loader:1069:27) at Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Module._load (node:internal/modules/cjs/loader:827:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) at node:internal/main/run_main_module:17:47

Node.js v18.0.0

CodePudding user response:

There are multiple errors in your code. The one triggering the error is the arrow function ([1, 2, 2, 3, 3, 3].uniq() => [1, 2, 3]) which is not a valid arrow function. What you want is to just print the result of [1, 2, 2, 3, 3, 3].uniq().

Array.prototype.uniq = function() {
  const narr = [];
  for (let i = 0; i < this.length; i  ) {
    if (!narr.includes(this[i])) {
      narr.push(this[i]);
    }
  }
  return narr;
}

console.log([1, 2, 2, 3, 3, 3].uniq());

Also it's not include() but includes(). Additionally you're loop will run exactly 0 times since i = 0 and your condition is i < 0. Change that to i < this.length.

By the way by using a Set you could implement the same behavior with complexity of O(n) instead of O(n²) like your current implementation.

Array.prototype.uniq = function() {
  return [...new Set(this)]
}

console.log([1, 2, 2, 3, 3, 3].uniq());

CodePudding user response:

Okey, you have a few mistakes:

  1. You need to declare narr
  2. Your condition in your for loop makes no sense i < 0. You need the length of the array this.length
  3. Typo include its includes

Array.prototype.uniq = function() {
  let narr = [];
  for (let i = 0; i < this.length; i  ) {
    if (!narr.includes(this[i])) {
      narr.push(this[i]);
    }
  }
  return narr;
}

console.log([1, 2, 2, 3, 3, 3].uniq());

  • Related