Estoy tratando de hacer una función para usar AND-Logicgate pero solo responde una matriz. Intenté usar toString() y join() pero no funcionan. Alguien puede ayudarme.
Aquí está el código:
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);Entonces, si la matriz contiene un false , la función prototipada .AND debería devolver false .
Use algunos para determinar si la matriz contiene un 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 thrownEn caso de que se le permita usar .reduce() , esto puede ser útil:
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); Otra variación puede ser usar .every así:
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]));