Verify that the user's input falls within a specified range before adding it to the result

Currently, I'm trying to implement validation on user input. The idea is that if a user enters a number between 1 and 10, I want to add a 0 in front of it. For example, if the user inputs 4, I would like to store the value 04. While I am comfortable doing this in C#, I am facing challenges when attempting to achieve the same functionality in TypeScript within a component class for my Angular 5 application.

public static void Main(string[] args)
{
    List<int> collection = new List<int>();
    for (int i = 1; i <= 10; i++)
    {
        collection.Add(i);
    }

    Console.WriteLine("Please enter your input below: " + "\n");
    string input = Console.ReadLine();
    Console.WriteLine();
    if (collection.Contains(Convert.ToInt32(input)))
    {
        Console.WriteLine("True" + "\n");
        var result = "0" + input;
        Console.WriteLine("Appended Result: " + result);
    }
    else 
    {
        Console.WriteLine("False");
    }
    Console.WriteLine();
}

The version of TypeScript I am working with is 2.3.3.0.

Answer №1

Converting your C# code directly gives you the following JavaScript equivalent:

var collection = [...Array(10).keys()];

var num = parseInt(prompt("Enter a number"));

if(collection.indexOf(num) !== -1) {
  console.log("0" + num);
} else {
  console.log(num);
}

TypeScript is amazing! Here’s an even more concise version of the code:

num = parseInt(prompt("Enter a number"));

num = num < 10 ? "0" + num : num;

console.log(num);

Answer №2

To accomplish this task, the following code can be utilized:

function paddedNumber(num: number, size: number): string {
    let s = num + "";
    while (s.length < size) 
        s = "0" + s;
    return s;
}

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 benefits of utilizing TypeScript's async await feature within the Node

I've encountered a challenge trying to accomplish the following tasks simultaneously: Developing in Node.js Coding in TypeScript Implementing async await Facilitating debugging Background: In my TypeScript-based Node.js project, I am incorporating ...

Tips for altering the design of an NgPrime element

Could you please provide me with the CSS values that are specified within the .myclass class? <style> .myclass { /* padding-right: 1.5em; */ border: 0; background-image: linear-gradient(#034076, #034076), linear-gradien ...

Execute the unknown function parameter

Trying to figure out how to convert an argument into an anonymous function, but struggling to find clear instructions. I know how to cast on variable assignment, but unsure if it's possible and how. Working with lodash where the typings specify the a ...

Guide on transferring the token and user information from the backend to the front-end

Here is the code from my userservice.ts file export class UserService { BASE_URL = "http://localhost:8082"; constructor(private httpClient:HttpClient) {} public login(loginData:any){ return this.httpClient.post(this.BASE_URL+"/au ...

Strategies for mitigating the use of Observables when passing data between Angular routes

When trying to exchange data between routes, the most effective method appears to be using a service. To ensure that data is updated and re-rendered in the view, we are required to utilize BehaviorSubject. Based on my understanding, a simple component wou ...

Toggle feature in React dropdown has a one-time activation

Is there a way to solve the issue with my React Dropdown component that closes but won't reopen properly? Could it be related to losing reference somehow? Here is the usage: https://codesandbox.io/s/react-typescript-obdgs import React, { useState, ...

Discover how to capture and process POST form data in Angular originated from external sources

I am currently building a website that utilizes Java for the backend and Angular for the frontend. I have encountered a scenario where external websites may transmit data to my site via POST form submissions. For example, ▼ General    & ...

Obtain the numerical representation of a weekday based on the name of

I am working with an array that looks like this: result = ['Saturday','Sunday'] My goal is to return the index for each of the days above, like this: detail= [6,7] I attempted the following approach to achieve this, but unfortunatel ...

What is the best way to implement push notifications for iOS using an Android device?

Having trouble sending notifications to iOS devices despite successfully sending them to Android devices? The iOS developer has provided the Apple device ID during registration, which is being used in the code. public string SendNotification(string messa ...

In C# Console, learn how to extract the first or first two digits from the string "12345-678" using the substring method

I'm currently working on a C# Console application where I need to replace hyphens with zeros to extend the length of a string from an identification card "123456-72." However, I'm encountering difficulties when it comes to sorting the array. My ...

Retaining selected items in Jquery UI Multiselect widget even after postback

I want to implement a GridView in asp.net that allows filtering on each column of the gridview, similar to Excel. To achieve this, I created a GridView and utilized the Jquery multiselect widget on the header of each column for filtering. <cc1:GridView ...

Is it possible to utilize IJS interop in ASP.NET 3 razor pages?

When using ASP.NET 3 with Blazor, I've encountered an issue where the IJSRuntime is not available. Attempting to include the runtime like this: @inject IJSRuntime JsRuntime; leads to the following error: The type or namespace name 'IJSRunti ...

Getting rid of one-time use resources in Windows desktop applications

It's common knowledge that we should throw away disposable items after we're done using them. But what about a disposable object, like a database context, that is used constantly in a windows desktop application's lifespan (like WPF or WinFo ...

Vue-i18n does not offer a default export option

Hello everyone! This is my first experience using vue-i18n in a project with TypeScript + Vue. Following the instructions from the official site, I installed it using yarn install vue-i18n. Next, I tried to import it into main.ts using import VueI18n from ...

What is the best way to display data stored in local storage using React and Typescript?

Is there a way for the data to be displayed on the browser below the save button when I click save? My setup involves using React with a TypeScript template. function ButtonDefaultExample(props: IButtonExampleProps) { const { disabled, checked } = pro ...

Tips for resolving Detected package downgrade alerts

I'm currently stuck on a frustrating problem and could really use some fresh ideas. I'm working in Visual Studio 2017 with a .NET Core 1.1 ASP.NET website that utilizes RavenDB. The issue I'm facing is in relation to 4 build warnings that ar ...

Utilizing jQuery to load a nested gridview efficiently for handling extensive datasets

I am trying to implement a nested gridview loading functionality using jQuery. I want to avoid reloading the data if it has already been loaded by the user, as retrieving detailed data is resource-intensive and time-consuming. Scenario: Let's conside ...

Using Angular to incorporate HighCharts for a gauge chart

I'm currently working on an Angular project where I need to display a statistic using a gauge chart. The thing is, I'm utilizing the HighCharts library and it's worth mentioning that I've successfully used other types of charts from Hig ...

Steps to Convert a Relative XPath to an Absolute XPath

Is there a way to convert a relative xpath of an object into its absolute path in C#? For example, something like absXpath = webelement.getxpath(); Thank you. ...

Customizing Angular tooltips based on specific conditions

Is it possible to implement a conditional tool tip? For instance, I am looking to only display the tool tip if cellData[id].length is greater than 120 within a div element. #solution <div matTooltip="Info about the action" class="{{cssCe ...