Home > Software design >  How to return boolean in an Array.prototype function?
How to return boolean in an Array.prototype function?

Time:03-20

Im trying to maken a function to use the AND-Logicgate but it only respons an array. I tryed useing toString() and join() but they dont work. Can anybody help me.

Here is the Code:

Array.prototype.AND = function() {
  var temp = true;
  for (let i = 0; i < this.length; i  ) {
    if (this[i] == false) {
      temp = false;
    }
  }
  while (this.length > 0) {
    this.pop();
  }
  this[0] = temp;
}

const test = [true, true, true, false];

test.AND();

console.log(test);

CodePudding user response:

So if the array contains a false, the prototyped function .AND should return false.

Use some to determine if the array contains a false.

const test = [true, true, true, false];
const test2 = [true, true, true, true];
const test3 = [true, "blah!", false];

// Make sure you do not overwrite an existing method
if(typeof(Array.prototype.AND) === "undefined"){
  Array.prototype.AND = function() {
    // Make sure the array only contains booleans
    if(this.some(item => typeof(item) !== "boolean")){
      throw `error: AND must be applied on boolean array only. Got ${JSON.stringify(this)}`
    }
    return !this.some(item => item === false)
  }
}

console.log(test.AND())   // false
console.log(test2.AND())  // true
console.log(test3.AND())  // error thrown

CodePudding user response:

In case one is allowed to use .reduce() this may be helpful:

const logicAndGate = arr => arr.reduce((a, b) => a && b, true);
      
const test = [true, true, true, false];
console.log(logicAndGate(test));
console.log(logicAndGate([true, true, true, true]));
console.log(logicAndGate([false, true]));
//test.AND();
//console.log(test);

Another variation may be using .every like this:

const logicAndGate = arr => arr.every(x => !!x);

console.log(logicAndGate([true, true, true, false]));
console.log(logicAndGate([true, true, true, true]));
console.log(logicAndGate([false, true]));

  • Related