Boolean Gates in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of Boolean values and a logical operator.

Our function should return a Boolean result based on sequentially applying the operator to the values in the array.

Example

Following is the code −

 Live Demo

const array = [true, true, false];
const op = 'AND';
function logicalCalc(array, op){
   var result = array[0];
   for(var i = 1; i < array.length; i++){
      if(op == "AND"){
         result = result && array[i];
      }
      if(op == "OR"){
         result = result || array[i];
      }
      if(op == "XOR"){
         result = result != array[i];
      }
   }
   return result;
}
console.log(logicalCalc(array, op));

Output

false
raja
Published on 17-Apr-2021 12:11:03
Advertisements