What is the best way to compile and assess logical operators and operands that are defined within an object?

How can I create a compiler that can evaluate logical operators and operands specified on an object, similar to MongoDB's $or and $and operators? For example:

return {
  $or: [
    foo: [...],
    bar: [...]
  ]
}

The compiler would call corresponding functions for each operand like foo and bar, then apply logical OR to the results. It should be able to handle nested logical operators as well. An example of a complex operation:

return {
  $or: [
    { 
      $and: [
        { foo: [...] }, 
        { bar: [...] }
      ] 
    }, 
    { baz: [...] }, 
    () => m < n
  ]
}

A simplified definition of the functions for foo, bar, and baz:

export const evalFoo = items => {
  return items.indexOf("foo") >= 0;
};

export const evalBar = items => {
  return items.indexOf("bar") >= 0;
};

export const evalBaz = items => {
  return items.indexOf("baz") >= 0;
};

Sample data:

Set 1

m = 4; n = 1; foo: ['foo', 'x']; bar: ['bar', 'y']; baz: ['baz', 'z']

RESULT = true; // because $and results to true.

Set 2

m = 4; n = 1; foo: ['x']; bar: ['y']; baz: ['x']

RESULT = false; // because m > n and $and results to false.

Set 3

m = 1; n = 3; foo: ['x']; bar: ['y']; baz: ['x']

RESULT = true; // because m < n.

Set 4

m = 3; n = 1; foo: ['x']; bar: ['bar']; baz: ['z']

RESULT = true; // because m > n, baz() is false and x and $and is false.

Answer №1

Consider implementing a solution similar to this, where you distinguish between $and, $or, and the respective functions.

This approach involves utilizing an object with keys representing array methods such as Array#every. This method acts like a logical 'and' by testing values in an object and returning true if all items, along with their callbacks, return a truthy value. Similarly, Array#some works analogously but requires only one truthy value from its callback.

Another object contains functions that can be accessed using the provided key.

The initial verification checks whether the parameter is a function. If it is, the result of the call is returned.

Following this, the parameter undergoes a check for being falsy (e.g., null) or not being an object. In such cases, the function terminates by returning false.

A destructuring assignment occurs to obtain a key/value pair from the object.

If the specified key is found in the operator object, its corresponding method, indicated by value, is then used to iterate over the value and return the result.

If the key corresponds to a function in the designated object, that function is invoked with value as its parameter before returning the result.

Lastly, if none of the previous conditions are met, the function returns false since the condition cannot be resolved.

function evaluate(object) {
    var operators = { $or: 'some', $and: 'every' },
        fns = {
            foo: items => items.indexOf("foo") >= 0,
            bar: items => items.indexOf("bar") >= 0,
            baz: items => items.indexOf("baz") >= 0
        },
        key,
        value;

    if (typeof object === 'function') return object();
    if (!object || typeof object !== 'object') return false;

    [key, value] = Object.entries(object)[0];

    if (key in operators) return value[operators[key]](evaluate);
    if (key in fns) return fns[key](value);
    return false;
}

var m = 4,
    n = 1,
    object = {
        $or: [
            {
                $and: [
                    { foo: ['foo', 'x'] },
                    { bar: ['bar', 'y'] }
                ]
            },
            { baz: ['baz', 'z'] },
            () => m < n
        ]
    },
    result = evaluate(object);

console.log(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

Exploring the Differences Between React Native and NativeScript for Cross-Platform

After hours of searching, I still can't decide on what to learn next. I want to be able to create a cross-platform app for web, android, and ios. Should I go with NativeScript or react native + Reactxp? Your experience and advice would be greatly appr ...

The module '../xcode' could not be located. This issue is occurring within React Native and Expo CLI, where the required stack cannot

Trying my hand at creating my first project using React Native in iOS with expo.io, I encountered an error when running the command "expo start": https://ibb.co/f2xsmpN https://i.sstatic.net/Uyxkk.png Despite attempts to reinstall and update Xcode, usin ...

A guide on updating an item in a basic JavaScript file with Node.js

This query pertains to Workbox and Webpack, but no prior knowledge of these libraries is necessary. Background Information (Optional) Currently using the InjectManifest plugin from Workbox 4.3.1 (workbox-webpack-plugin). While this version provides the o ...

What is the best way to iterate through a designated key in every object within a JSON dataset and store it in a variable called `data` for use with

I am looking to create a line chart displaying stock prices, utilizing JSON data to populate the chart. Let's say I have some JSON data: [ { "close": 116.59, "high": 117.49, "low": 116.22, "open& ...

The Bootstrap modal is making the content below shift to the left

Encountering an issue with our Bootstrap modal causing the content to align left, specifically on certain Macbooks using Chrome. Interestingly, the problem is present on my co-worker's computer but not on mine, even though the specifications are the s ...

Display loader while waiting for file to be loaded

I am utilizing ajax to retrieve a file. The loading animation is functioning properly with the ajax request, however, the file size is notably large. I am interested in implementing a preloader that will display until the file has finished loading. ...

What is the process of incorporating a JS engine into an ASP.NET Core MVC React application?

An error will be displayed by the upcoming service. reference missing services.RegisterJsEngineSwitcher(settings => settings.DefaultEngineName = V8JsEngine.EngineName) .AddV8(); ...

Keep Modal Open During Ajax Requests

After clicking the edit button and making changes to the form, I want to reset the page background. However, when I click edit, the form is edited and the modal closes but does not completely close. The div ajaxshow is a layout element that displays the a ...

Issue encountered while attempting to transfer data via the $.ajax method

I created a poll form using radio buttons. To submit the form, I utilized $.ajax. However, when I tried using $("#polling").serialize() to gather the data, nothing was sent or requested... Could the issue be related to the radio buttons? $(function( ...

Having trouble locating the module while importing MP3 files in a React project

UPDATE The issue stemmed from my limited understanding of the environment I was working in, but the responses provided below may be helpful for others facing similar challenges. EDIT: It appears that there is a problem with trying to import an mp3 file in ...

"Modify the color of a div element by changing it from the color name to the hexadecimal

Is there a way to use color codes instead of typical color names, like #e06666 for red? content.push('<p><div class="color red"></div>Whole Foods Market</p>'); Any suggestions on how to achieve this? ...

The function(result) is triggered when an http.get request is made

Can anyone help me figure out why my function is jumping after completing the request? It seems to be skipping over .then(function(result){ }. I suspect that the issue might be related to the <a> element with an onclick attribute containing an href ...

Tips on incorporating a changing variable into a JavaScript Shader

I have successfully created a primitive sphere using THREE.SphereGeometry and applied a displacement shader to give it a bumpy effect. My goal now is to animate the scale of the bumps based on input volume from the microphone. Despite my efforts, I am stru ...

Setting `tabBarVisible` to false does not function properly within a stackNavigation nested element

Details on my project dependencies: "react-navigation": "^3.6.0", "expo": "^32.0.0" I'm working with a TabNavigator that contains redirections to child components, which are StackNavigators. However, I'm facing an issue where I am unable to hide ...

When I try to access localhost, it directs me to http://localhost:3000/myprofile%20 instead of localhost:/3000/myprofile

Every time I try to log into my profile page with the correct login credentials, I get redirected to http://localhost:3000/myprofile%20, but then receive a 404 error. This is what my code looks like: // Login Route router.post('/login', functi ...

Updating a database on ASP.NET without the need to refresh the page

We are developing a user-friendly application with ASP.NET MVC that focuses on uploading pictures and rating them. The app includes two voting buttons, "like" and "dislike". https://i.sstatic.net/Z3dp5.png Whenever the like button (green) is clicked, the ...

Using Lodash library to iterate through a collection using the _.forEach method

Currently, I am attempting to implement the lodash forEach method within a structure where a nested function is being used to call a mongo database. var jobs = []; _.forEach(ids, function(id) { JobRequest.findByJobId(id, function(err, result) { ...

Error: It is not possible to assign a value to the Request property of the Object since it only has a getter method

Encountering issues while attempting to deploy my Typescript Next.js application on Vercel. The build process fails despite functioning correctly and building without errors locally. Uncertain about the root cause of the error or how to resolve it. The f ...

An interactive data organizing tool on a website

Similar Question: Is there a Spreadsheet-like control for web applications? I am exploring different tools available, unsure of how to implement what I have in mind. Currently, my webpage uses javascript to parse user-provided information. Users copy ...

Cannot Display CSS Background Image Locally

Apologies for the simple inquiry, but I am facing an issue with displaying my background image using background-image:url() in the CSS. Strangely, it does not work with this method, but when I use content:url(); it works just fine. Interestingly, backgrou ...