Develop a function that transforms a provided string

I need assistance creating a function that will convert a given string into the specified output format shown below:

// Input
const optionRule = '{1069} AND ({1070} OR {1071} OR {1072}) AND {1244} AND ({1245} OR {1339})';

// Output Example
/* const output = {
  and: [
    1069,
    { or: [1070, 1071, 1072] },
    1244,
    { or: [1245, 1339] },
  ]
}; */

let result = 'result'

console.log('result:', result);

Seeking guidance on how to achieve this task. Any help would be greatly appreciated.

Answer №1

Why rely solely on others for solutions? Instead, challenge yourself to work through the problem by including some code in your question. Remember, this community is here to assist you. I can provide a straightforward solution if needed.

const transformString = (str) => {
    const strArray = str.split(' AND ')
    const result = strArray.map(item => {
        let temp = item.split(' OR ')
        if (temp.length < 2) {
            return Number(temp[0].replace(/[{()}]/g, ''))
        } else {
            let tempValues = temp.map(i => Number(i.replace(/[{()}]/g, '')))
            return {
                'or': tempValues
            }
        }
    })
    return result
}
console.log(transformString(optionRule))

Answer №2

function processInput(inputArray) {
    let resultObject = {}
    let newArray = []
    let stringArray = inputArray.split(' AND ')
    stringArray.forEach(string => {
        if (string.includes('OR')) {
            newArray.push({
                or: string.match(/\d+/g).map(value => +value),
            })
        } else {
            newArray.push(Number(string.match(/\d+/g)))
        }
    })
    resultObject.and = newArray
    return resultObject
}
console.log(processInput(optionRule))

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

Form featuring a mandatory checkbox that must be selected in order to proceed; failure to do so will result in an

So here’s the situation: I have a form with a checkbox for agreeing to the terms of service, and I want to make sure it is checked before proceeding with the donation process. I only have the HTML code and no idea how to implement this functionality. Ide ...

Exploring the .map() Method in ReactJS

Would it be feasible to integrate another Postgres database table into the current mapping displayed in this code? It would be ideal if it could be done using some sort of array function. {items.map(item => ( <tr key={item.id}& ...

Display updated schedule based on the refreshed array using jQuery

Currently in the middle of a project that involves displaying a charge schedule based on user-inputted variables. After updating the array with a priority number calculated from the data, I am struggling to generate the schedule using the updated array. T ...

What is the best way to increase a specific value in an array of objects once it has been located (using findOne()), but before it is

I'm looking for a more efficient way to update an object within an array of schemas in one database request instead of two. Currently, I use findOneAndUpdate() to increment the field if the object already exists, and then I have to use update() if the ...

Shader in THREE.js only appears when the window is resized

I recently started working with THREE.js and have been experimenting with shaders. Strangely, I've noticed that this particular shader only displays correctly when I resize the window. You can find the code here. Any ideas on why it's behaving th ...

What is the best way to extract and count specific values from a JSON file using JavaScript?

My JSON data looks like this: /api/v1/volumes: [ { "id": "vol1", "status": "UP", "sto": "sto1", "statusTime": 1558525963000, "resources": { "disk": 20000000 }, "used_resources": { "disk": 15000000 }, "las ...

Unable to redirect with Asp response.redirect

I have a Login popup form where I use an ajax post request to Login.asp script in order to prevent the page from going to the POST URL after submission. <script> $(function() { $('#contactForm').submit(function(e){ e.preventDe ...

The variable "artikel" is not defined in the view template located at C:xampphtdocsuts esourcesviewslayoutshome.blade.php

A variable named "artikel" is not defined (0) (View: C:\xampp\htdocs\uts\resources\views\layouts\home.blade.php) @if($artikel) @foreach($artikel as $d) <h3> {{ $d->judul }}</h3> <h3> {{ $d->penuli ...

The array is being initialized with a higher number of elements than prescribed

Python: list = [1, 2, 3, 4, 5, 6, 7] print(list) When executed, it displays the list of integers: [1, 2, 3, 4, 5, 6, 7] The output accurately reflects the values stored in the list without any additional information. ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

Can someone help me identify the table rows that are adjacent to a dropped row in a jQueryUI Sortable setup?

My current setup involves using the jQueryUI Sortable plugin on a table, and thankfully everything appears to be functioning correctly. Both the HTML and JavaScript are passing validation. However, I am faced with the challenge of finding a way to identi ...

The AJAX request function in JavaScript seems to be failing to return any response

I am currently working on a registration page where users can check the availability of their selected username without having to reload the entire page. The PHP script 'usernameAJAX.php' is responsible for querying the database and returning a r ...

Loading data into a Dojo ItemFileReadStore using Grails and the "render as JSON" method

I have developed a controller method that generates a JSON "file" on-the-fly when the corresponding URL is accessed. This file exists in memory and not saved on disk, as it's dynamically created when the URL is hit. I'm attempting to utilize this ...

Show or hide a div in Vuejs based on checkbox selection

I've been attempting to toggle the visibility of a container div using Vuejs with no success. I've tried two different methods, but neither seem to work for me. Here is Method 1: <body> <div class="checkbox" id = "selector"& ...

Java Entity Framework Indexing Tables

I am currently utilizing ASP.Net Core and have implemented EntityFramework to create a controller with views. Specifically, I am in the process of enhancing the Index view to make it dynamic with dropdown selections. I have successfully completed everythin ...

Utilizing HTML's multiple input type color feature to save selected colors directly to the database

I am currently using the input type color to select colors for customizing my site. I save the selected color to a database and then retrieve it to apply it to different areas of the site. This works well for a single input type color, but now I have mul ...

JavaScript Await Dynamic User Input

I have implemented a modified version of a script for generating random numbers in multiple columns of a spreadsheet, inspired by Tim Cooper's solution on stackoverflow. This script works by selecting a range of cells and running it from an onOpen men ...

Leverage the router through the getServerSideProps method

My goal is to automatically redirect the user to the login page if their token has expired. I need to handle this in the getServerSideProps method where I make a request to the server for data. If the request is unauthorized, I want to use the useRouter ho ...

Having trouble with my loop using Jquery's $.get method

Having an issue with Jquery mobile / JavaScript I'm struggling to properly loop through the different values of data in my "get" function, where it should be sending ...cmd=PC&data=06464ff ...cmd=PC&data=16464ff ...cmd=PC&data=26464ff ...

Is there a way to programmatically fetch files from a MySql / Node.js server?

I've been working on my CRUD app and I'm currently focusing on downloading files from a MySql Nodejs server. Here are the steps I have accomplished so far: I created a function in userContoller.js to query the MySql database for the id=179 (just ...