Array[object..] logical operators

I am currently working with Boolean and logical operators using code like this:

Just so you know, I want to convert object values and logic into an array to perform logical operations. For example: object1.logic object.operators object2.logic as either true or false.

const input: Array<any> = [
    {
        type: "basic",
        value: true,
        logic: "or"
    },
    {
        type: "basic",
        value: false,
        logic: "and"
    },
    {
        type: "basic",
        value: true,
        logic: "and"
    },


I expect the result to be equivalent to:

 true || false && true

Does anyone have a solution for this particular issue?

Answer №1

To achieve the desired outcome, simply utilize the reduce operator to create a new operator object that combines the logic of previous operators with the values or computations of the current one.

let input = [{
    type: "basic",
    value: true,
    logic: "or"
  },
  {
    type: "basic",
    value: false,
    logic: "and"
  },
  {
    type: "basic",
    value: true,
    logic: "and"
  }
]

// In case type is not considered 

let result = input.reduce((op1, op2) => ({
  logic: op2.logic,
  value: op1.logic === 'or' ? op1.value || op2.value : op1.value && op2.value
}));
// For multiple || and && operations, you can create a function with switch cases and call it here.

console.log(result);

If you wish to control the sequence of operations:

let input = [{
    type: "basic",
    value: true,
    logic: "or"
  },
  {
    type: "basic",
    value: false,
    logic: "and"
  },
  {
    type: "basic",
    value: true,
    logic: "and"
  }
]

// Logic: and - or
// Operation: (boolean, boolean) => boolean; 
let processOperation = (logic, operation, arr, op) => {
  // If empty, return the first element
  if (!arr.length) return [op];

  let prevOp = arr[arr.length - 1];

  if (prevOp.logic === logic) {
    // Replace previous operation with the result
    arr.pop()
    arr.push({
      logic: op.logic,
      value: operation(prevOp.value, op.value)
    });
  } else {
    arr.push(op); // If operation logic does not match, push for future processing
  }
  return arr;
}

let result = input
  .reduce(processOperation.bind(this, 'and', (a, b) => a && b), [])
  .reduce(processOperation.bind(this, 'or', (a, b) => a || b), []);
// The order is determined by the chain sequence

// result[0].value will give the solution
console.log('answer', result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After integrating React Query into my project, all my content vanishes mysteriously

Currently, I am utilizing TypeScript and React in my project with the goal of fetching data from an API. To achieve this, I decided to incorporate React Query into the mix. import "./App.css"; import Nav from "./components/Navbar"; impo ...

A beginner's guide to integrating ChartJS with React

Trying to incorporate ChartJS into a React component but unsure of how to proceed. First step is to create a canvas element following the instructions found at https://www.chartjs.org/docs/latest/getting-started/usage.html#creating-a-chart. Next, need to ...

Tips for accurately documenting the Props parameter in a React component with Destructuring assignment

Attempting to create JSDocs for a React component using destructuring assignment to access props: const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... } The issue arises when trying to document multiple parameters in JSDocs ...

Angular 6 allows for the use of radio buttons to dynamically enable or disable corresponding fields

Here is the HTML code for a row containing radio button selections: <div class="form-row"> <div class="col-md-3 mb-3"> <div class = "form-group form-inline col-md-12 mb-3"> <div class="form-check form-check-inl ...

Jest is throwing an error: Unable to access property from undefined while trying to import from a custom

I developed a package called @package/test. It functions perfectly when imported into a new, empty React TypeScript application. However, issues arise within Jest test suites. The usage of the CommonJS package version causes Jest to throw an error: Test ...

Transforming Boolean data types into text within an Angular 2 client-side application

Query I'm currently working on retrieving data from an API and displaying it in a table. One of the columns includes a status attribute that returns either true or false values. However, I would like to display "Active" or "Block" instead on the clie ...

What is the way to declare a prop as optional in Svelte using TypeScript?

I am facing an issue in declaring an optional prop in Svelte with TypeScript. The error message I receive is "Declaration or statement expected". Can someone guide me on how to correctly declare the prop? Definition of My Type: export enum MyVariants { ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

I am puzzled as to why I am still facing the error message: "'node' is not recognized as an internal or external command, operable program or batch file."

I'm in the process of setting up typescript for a new node project. Here are the steps I've taken so far: Installing typescript: npm i --save-dev typescript Installing ts-node: npm i --save-dev ts-node Installing the types definition for node ...

Check out the attributes of a class

I have a TypeScript class that is defined like this: export class MyModel { ID: number; TYPE_ID: number; RECOMMENDED_HOURS: number; UNASSIGNED_HOURS: number; } In a different .ts file, I instantiate this class within a component: export class My ...

transition from mapStateToProps to using hooks

Just dipping my toes into the world of React (hooks) and learning by writing code. I'm grappling with converting MapStateToProps to hooks, specifically stuck on one part just before 'currentItem'. Here's the original code snippet: co ...

Creating a definition for the use of sweet alerts within a service and incorporating them through

Implementing sweet alert for displaying alert messages in angularJS2/typescript. Due to the repetitive nature of this code in different parts of the application, a service was created. @Injectable() export class AlertMessageService { constructor(pr ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

What is the best time to initialize .env variables in a NodeJS application?

Building a NodeJS Express REST API with TypeScript requires loading environment variables using the dotenv package. In my code, I access the .env variables in two different files: index.ts, which serves as the entry point, and in a separate file called My ...

When defining functions in Typescript, the new() syntax is used

Can you explain the purpose of the type declaration for dialogComponent in this specific Typescript code snippet? createDialog(dialogComponent: { new(): DialogComponent }) : Promise<ComponentRef<DialogComponent>> { ... } (Referenced from ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

What is the process for including an extra track in Twilio Video?

Since updating the twilio-video JS SDK from version 1.x to 2.x, I've encountered an issue when trying to add an additional device. An example of the error message is as follows: ERROR TypeError: transceiver.sender.replaceTrack(...).then(...).finally i ...

Input values that are true, or in other words, fulfill conditions for truthiness

Is there a specific data type in TypeScript to represent truthy values? Here's the method I'm working with: Object.keys(lck.lockholders).length; enqueue(k: any, obj?: any): void It seems like TypeScript allows checking for empty strings &ap ...

Passing along the mouse event to the containing canvas element that utilizes chart.js

Recently, I created a custom tooltip for my chart.js chart by implementing a div that moves above the chart. While it works well, I noticed that the tooltip is capturing mouse events rather than propagating them to the parent element (the chart) for updati ...

Having trouble retrieving a value from a reference object in React Typescript?

Struggling with a login form issue in my React TypeScript project. Below is the code for the react login form: login-form.tsx import * as React from 'react'; import { Button, FormGroup, Input, Label } from 'reactstrap' ...