Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

333
Vistas
How to return boolean in an Array.prototype function?

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);

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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]));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda