Achieve a new version without relying on conditions

I am looking to achieve the same functionality as the code below but without using any condition statements.

HelloFunction(x){
    If(x<0){
       Console.log("greater");
    }Else{
       Console.log("smaller");
    }
};

HelloFunction(1);
HelloFunction(-1);

Answer №1

Utilizing an Object may seem unconventional, whereas employing an if...else statement or its succinct ternary form can better communicate the underlying logic, making it more transparent.

function Hello(x) {
  const lt = {
    true: "smaller",
    false: "greater"
  };

  console.log(lt[x < 0]);
};

Hello(1);
Hello(-1);

Answer №2

It might seem a bit unconventional to actually implement this, and it could be considered too specific for your particular scenario but...:

const greet = (x) => {
  const check = x < 0;
  console.log("positive".repeat(!check) + "negative".repeat(check));
};

greet(-1);
greet(1);

Expanding on @Teemu's idea, a more adaptable approach could be:

const if_else = (condition_fn, if_function, else_function = (x) => x) =>
  [else_function, if_function][+condition_fn()]();

const greet = (x) =>
  if_else(
    () => x < 0,
    () => console.log('positive'),
    () => console.log('negative')
  );

greet(-1);
greet(1);

Answer №3

@Teemu provided insight on accomplishing the task without any branching, which can prove advantageous in certain situations (see this discussion: Why is processing a sorted array faster than processing an unsorted array?).

function greeting(y) {
  console.log(['bigger', 'smaller'][+(y < 0)]);
}

greeting(1);
greeting(-1);

However, it must be noted that achieving desired functionality based on a specific condition inherently involves a form of conditional.

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

My variable from subscribe is inaccessible to Angular2's NgIf

My goal is to display a spinner on my application while the data is being loaded. To achieve this, I set a variable named IsBusy to True before making the service call, and once the call is complete, I set IsBusy to false. However, I am facing an issue wh ...

Angular: Unable to access values of non-existent data (reading '0')

I'm encountering an error when trying to import an excel file using the following code Angular Ag Grid Excel Import Cannot read properties of undefined (reading '0') I'm attempting to import a file named Book.csv, and wondering if thi ...

Despite using callbacks when passing props in React JS components, the rerendering still occurs

In my React project, I implemented callbacks to prevent excessive rerendering due to the large amount of data being displayed and numerous buttons that trigger these rerenderings when clicked by the user. The useCallback hooks are effective in preventing ...

Tips for implementing validation in JavaScript

I'm brand new to learning Javascript. Recently, I created a template for a login page and it's working perfectly fine. However, I am struggling with setting up validation and navigation. My goal is to redirect the user to another page if their us ...

Tips for improving the loading speed of a table during scrolling with JavaScript

Is there a way to speed up the loading time of a <table> with 20000 rows? As I scroll through the page, it feels very sluggish and takes around 4-5 seconds to load the remaining table data. I'm unsure how to tackle this issue, which is why I h ...

Here's a revised version: "How to link a lambda layer with a function in a serverless.ts file using the

When working with the serverless framework using the typescript template, a serverless.ts file is generated. I am currently integrating lambda layers with existing functions and encountering a typescript error. The error message reads: "Type '{ Ref: ...

Data is successfully being stored in an array in AngularJS, however, it is not appearing in the user interface

Having an issue with displaying updated data on my UI. I am successfully pushing data into the database and an array using Angular 2-way binding. The data is being pushed as confirmed by the console, but it's not showing up on the user interface. Con ...

TSX is throwing an error: "No matching overload found for this call."

Just starting out with React and TypeScript here! I tried passing the propTypes into a styled-component and ran into this error message: Oh no, there's an issue with the overloads. Overload 1 of 2 seems to be missing some properties. Overload 2 of ...

Guide for Extracting a String in JavaScript that Includes Numerals for Color Code Alteration, Resulting in Formats like 32m+ or 31m-

Attempting to create a Firebase cloud function in JavaScript that sends email notifications for any changes in the Firebase remote config. Upon each remote config change, the string received is in the following format: { parameters: { [32m+ newer_value: ...

Customized webpage content using AJAX for interactive map selections

I have integrated JQVMaps into a WordPress website to display a dynamic world map. The goal is to update the content of the page based on the region that the user clicks. Below is a snippet of the code I have implemented as a proof of concept: <div ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

Ways to activate onChange multiple times for a single item within material ui's autocomplete feature

I am utilizing the autocomplete component in the Material UI. Upon selecting an item, the onChange props are triggered and certain actions are performed. However, I am encountering an issue where I can select the same object multiple times without the on ...

Can a props be retrieved and passed as an argument to a function?

My goal is to retrieve a prop from MapsStateToProps using react-redux's connect and then pass it to a child component. This prop serves as an argument for a function, which in turn returns something that becomes the state of the child component. Alth ...

Issue with Swiper js "autoheight" not resizing correctly for the height of the first slide upon page initialization

Hey everyone, I'm encountering a problem with my reactapp and I'm not sure how to resolve it. I've spent a considerable amount of time searching on stackoverflow but haven't come across any helpful solutions. The issue is related to a ...

What is the method for converting a string[] array to a record<string, boolean> format in typescript?

I have a string array that contains values I want to keep and use to create a new array called Record. For each value in the userValue array. For example: userValue: string[] = ["1111","2222","3333","4444"]; selectedOptions: Record<string, boole ...

VSCode mistakenly detecting Sequelize findOne and findAll return type as any inferences

I have a model defined using Sequelize as shown below: import { Sequelize, Model, BuildOptions, DataTypes } from 'sequelize'; interface User extends Model { readonly id: string; email: string; name: string; password_hash: string; reado ...

A guide on utilizing Stripe's payment_intent_data feature to automatically send an email to the customer following a successful transaction

I am struggling to send an email to the client after a successful payment. The documentation mentions setting "payment_intent_data.receipt_email", but my code below is not working as expected (no emails are being received). How should I properly configur ...

What is the best way to handle resolving a promise nested within another promise and retrieving the result within a controller?

I have a situation where I need to modify the result of a promise returned by a function in one service and make this altered value accessible to my controllers from another service. angular.module('test').service("service1", function($q) { ...

locate missing Gutenberg block on map

/** * Custom Block: display-mobile-advertising * * This block registers a basic block with Gutenberg that renders and saves content without any interactivity. */ // Import CSS. import { TextareaControl } from '@wordpress/components'; import ...

Retrieve JSON data and use a button to sort and display markers on a Google Map

Is it possible to modify my function in order to use different PHP files with separate buttons without duplicating the code? Currently, I have a function that displays markers on an external HTML page when a button is clicked. The data is retrieved from fi ...