Typescript generate random string

Create random string in typescript [duplicate]

and i wanted to assign the randomly generated numbers to certain symbols like 1 = cherry, 2 = bell and so on so i could print out the results in symbol form at the end. i tried putting the symbols as strings in an array and assigning the numbers to the elements in the array in each slot functions but it didn’t work out. is there a way to do this?

Create random string in typescript [duplicate]

How do I create a random string in typescript consisting of the alphabet [a-z0-9]? It should always consist of 32 digits. And also there should be no redundant strings.

makeString(): string < let outString: string = ''; let inOptions: string = 'abcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 32; i++) < outString += inOptions.charAt(Math.floor(Math.random() * inOptions.length)); >return outString; > result: string = this.makeString(); 

Generate random password string with requirements in, This will generate three random strings from the given charsets (letter, number, either) and then scramble the result. Please note the below uses sort () for illustrative purposes only. For production use, replace the below sort () function with a shuffle function such as Durstenfeld. First, as a function:

Читайте также:  Иван Фубаров

How to generate a new random string each time, in a given string text, a regex is satisfied?

I have splited the resulted text of a file, what I need to do is to rename the header of that file, so I have taken the first indice of the sp (the header) and for each word in this header, I want to replace them with a different random string. But I have the same random string for each satisfied regex.

var sp = reader.result.split("\n"); var randomString = Math.random().toString(36).substr(5, 5) for ( let i in sp ) < if (i == 0) < sp[i] = sp[i].replace(regex, randomString) >> 

So you fetch that header text from your file and then you want to extract each word from it and then replace it with some random string. Here’s the code for it.

On a side note Math.random() is not good enough, you need the crypto API

function generateHash (length = null) < const array = new Uint8Array((length || 64) / 2) window.crypto.getRandomValues(array) return Array.from(array, dec =>< return dec.toString(16).padStart(2, '0') >).join('') > const header = 'One word and another word' const modified = header.split(' ').map(val => generateHash(12)).join(' ') console.log(modified)

Ts generate random string Code Example, var crypto = require(«crypto»); var // «bb5dc8842ca31d4603d6aa11448d1654»

How to get a random enum in TypeScript?

How to get a random item from an enumeration?

enum Colors < Red, Green, Blue >function getRandomColor(): Color < // return a random Color (Red, Green, Blue) here >

After much inspiration from the other solutions, and the keyof keyword, here is a generic method that returns a typesafe random enum .

function randomEnum(anEnum: T): TTypescript generate random string < const enumValues = Object.keys(anEnum) .map(n =>Number.parseInt(n)) .filter(n => !Number.isNaN(n)) as unknown as TTypescript generate random string[] const randomIndex = Math.floor(Math.random() * enumValues.length) const randomEnumValue = enumValues[randomIndex] return randomEnumValue; > 
interface MyEnum const myRandomValue = randomEnum(MyEnum) 

myRandomValue will be of type MyEnum .

Most of the above answers are returning the enum keys, but don’t we really care about the enum values?

If you are using lodash, this is actually as simple as:

_.sample(Object.values(myEnum)) as MyEnum 

The casting is unfortunately necessary as this returns a type of any . 🙁

If you’re not using lodash, or you want this as its own function, we can still get a type-safe random enum by modifying @Steven Spungin’s answer to look like:

function randomEnum(anEnum: T): TTypescript generate random string

How about this, using Object.values from es2017 (not supported by IE and support in other browsers is more recent):

function randEnumValue(enumObj: T): TTypescript generate random string

This is the best I could come up with, but it looks like a hack and depends on the implementation of enum in TypeScript, which I’m not sure is guaranteed to stay the same.

Given an enumeration such as

if we console.log it, we get the following output.

This means we can go through this object’s keys and grab only numeric values, like this:

const enumValues = Object.keys(Color) .map(n => Number.parseInt(n)) .filter(n => !Number.isNaN(n)) 

In our case, enumValues is now [0, 1, 2] . We now only have to pick one of these, at random. There’s a good implementation of a function which returns a random integer between two values, which is exactly what we need to randomly select an index.

const randomIndex = getRandomInt(0, enumValues.length) 

Now we just pick the random enumeration value:

const randomEnumValue = enumValues[randomIndex] 

Typescript random letter Code Example, how to randomly generate a string in ts; var str1=’hello world’; var str2=’welcome to typescript’; function test(str1:string,str2:string) < console.log(str1.concat(str2)) console.log(str1.concat( 'mr','vinay')) >test(); console.log(str1.concat(str2)) fibonacci counter in typescript; tss from gene granges ; TypeScript interface for …

How can i assign a randomly generated integer to a string in C?

i’m trying to make a slot machine type thing and i wanted to assign the randomly generated numbers to certain symbols like 1 = cherry, 2 = bell and so on so i could print out the results in symbol form at the end.

i tried putting the symbols as strings in an array and assigning the numbers to the elements in the array in each slot functions but it didn’t work out. is there a way to do this?

here’s the code i’ve written so far, minus the array attempts. any suggestions would be helpful! 😀

EDIT: here’s an example of what i’ve tried doing on one of the slots but it keeps saying i need a cast to assign the integer from a pointer (i’ve tried searching online but idk how to do this)

char * slotOne(int randOne, const char *symbols[]) < randOne = rand() % 4 + 1; if (randOne = 1) < randOne = *symbols; >if (randOne = 2) < randOne = *(symbols+1); >if (randOne = 3) < randOne = *(symbols+2); >else < randOne = *(symbols+3); >return randOne; > 

this is the part of my main function where i’ve tried declaring the string array:

int main() < int x, one, two, three; const char *symbols[4] = ; srand(time(NULL)); one = slotOne(x); two = slotTwo(x); three = slotThree(x); printf("%s - %s - %s\n", one, two, three); //. > 

not sure if %s or %c is the right type too.

Code is assigning = when it should compare == .

// if (randOne = 1) if (randOne == 1) 

The last if () < . >else < . >will cause one of the 2 blocks to execute. OP wants an if () < . >else if () < . >else < . >tree.

// Problem code if (randOne = 3) < randOne = *(symbols+2); >else
if (randOne == 1) < randOne = *symbols; >else if (randOne == 2) < randOne = *(symbols+1); >else if (randOne == 3) < randOne = *(symbols+2); >else

Or consider a coded solution:

But code needs to return a pointer to a string not an int and has no need to pass in randOne as a parameter.

const char * slotOne(const char *symbols[])

Calling code also needs to adjust to receive a const char * , not an int .

// int one; // one = slotOne(x); const char *one = slotOne(symbols); 

How to generate random JSON string in Java?, It’s a library specialised in generating all kind of «fake» data. Check out the documentation to see what you can «fake» and how. There is a wiki page that shows you how you can generate a Random JSON: MockNeat mockNeat = MockNeat.threadLocal (); Gson gson = new GsonBuilder () .setPrettyPrinting () …

Источник

ts-randomstring

A simple Node-based library written in TypeScript that allows you to generate random strings (a)synchronously.

Installation

npm install ts-randomstring 

Usage

Consumers are able to use both synchronous and asynchrounous (via callback) functions and class methods.

Exported function examples:

import < generateRandomString >from "ts-randomstring/lib" // Synchronously generate a random string via function. const randomString = generateRandomString(); 
import < generateRandomStringAsync >from "ts-randomstring/lib" // Asynchronously generate a random string via function and callback. generateRandomStringAsync((error, randomString) => < if (error === undefined) < // Use your randomly generated string. console.log(randomString); >else < // Handle error. console.log(error); >>); 

Exported class method examples:

import < RandomString >from "ts-randomstring/lib" // Synchronously generate a random string via class method. const randomString = new RandomString(); const rand = randomString.generate(); 
import < RandomString >from "ts-randomstring/lib" // Asynchronously generate a random string via class method callback. const randomString = new RandomString(); randomString.generateAsync((error, rand) => < if (error === undefined) < // Use your randomly generated string. console.log(rand); >else < // Handle error. console.log(error); >>); 

Examples of random string options (demonstrated via functions):

import < generateRandomString >from "ts-randomstring/lib" // Setting length. const randomString = generateRandomString(< length: 128 >); 
import < generateRandomString, CharacterSetType >from "ts-randomstring/lib" // Setting length and character set. const randomString = generateRandomString(< length: 64, charSetType: CharacterSetType.Hex >); 
import < generateRandomString, CharacterSetType, Capitalisation >from "ts-randomstring/lib" // Setting length, character set, and capitalisation style. const randomString = generateRandomString(< length: 32, charSetType: CharacterSetType.Alphanumeric, capitalisation: Capitalisation.Uppercase >); 

Options in-depth

length : number (default= 32 ); sets the length of the required random string

charSetType : CharacterSetType (default= CharacterSetType.Alphanumeric ); sets the type of the character set used for random string generation.

capitalisation : Capitalisation (default= Capitalisation.Mixed ); sets the capitalisation style of the random string.

Valid CharacterSetType and Capitalisation enum values:

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A library used for generating random strings, written in TypeScript and based on Node.

License

c-schembri/ts-randomstring

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A simple Node-based library written in TypeScript that allows you to generate random strings (a)synchronously.

npm install ts-randomstring 

Consumers are able to use both synchronous and asynchrounous (via callback) functions and class methods.

Exported function examples:

import < generateRandomString >from "ts-randomstring/lib" // Synchronously generate a random string via function. const randomString = generateRandomString(); 
import < generateRandomStringAsync >from "ts-randomstring/lib" // Asynchronously generate a random string via function and callback. generateRandomStringAsync((error, randomString) => < if (error === undefined) < // Use your randomly generated string. console.log(randomString); >else < // Handle error. console.log(error); >>); 

Exported class method examples:

import < RandomString >from "ts-randomstring/lib" // Synchronously generate a random string via class method. const randomString = new RandomString(); const rand = randomString.generate(); 
import < RandomString >from "ts-randomstring/lib" // Asynchronously generate a random string via class method callback. const randomString = new RandomString(); randomString.generateAsync((error, rand) => < if (error === undefined) < // Use your randomly generated string. console.log(rand); >else < // Handle error. console.log(error); >>); 

Examples of random string options (demonstrated via functions):

import < generateRandomString >from "ts-randomstring/lib" // Setting length. const randomString = generateRandomString(< length: 128 >); 
import < generateRandomString, CharacterSetType >from "ts-randomstring/lib" // Setting length and character set. const randomString = generateRandomString(< length: 64, charSetType: CharacterSetType.Hex >); 
import < generateRandomString, CharacterSetType, Capitalisation >from "ts-randomstring/lib" // Setting length, character set, and capitalisation style. const randomString = generateRandomString(< length: 32, charSetType: CharacterSetType.Alphanumeric, capitalisation: Capitalisation.Uppercase >); 

length : number (default= 32 ); sets the length of the required random string

charSetType : CharacterSetType (default= CharacterSetType.Alphanumeric ); sets the type of the character set used for random string generation.

capitalisation : Capitalisation (default= Capitalisation.Mixed ); sets the capitalisation style of the random string.

Valid CharacterSetType and Capitalisation enum values:

About

A library used for generating random strings, written in TypeScript and based on Node.

Источник

Оцените статью