-1

I would like to convert this Python code into JavaScript using Node.JS so I can use it in my application. How may I do this in Node.JS JavaScript.

Current Python code:

import random
import string

chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
ERC = []
for i in list(range(15)):
    ERC[i] = '-'.join(''.join(random.choice(chars) for i in range(5)) for i in range(4))

The above code gets random characters from the variable which acts as a whitelist of alphanumeric characters I want to use, the format is 4 segments of 5 random characters separated by a dash. I have looked and found random-js but I haven't found it very concluding for my needs. I need something like node-randomstring, but that the alphabetical characters are in upper case. Math.random() doesn't work for me because it returns numbers between 0 and 1.

An example of the final output (from my code) looks like SY51R-APE9S-WM8ZC-L3ZP2

wolfy1339
  • 784
  • 2
  • 7
  • 23
  • 2
    I assume you mean just Javascript in which case yes. – Untitled123 Jan 02 '16 at 18:29
  • Yes, I did. I know how to do everything except for the random choice of characters, I'm trying to figure out how to do it in NodeJS – wolfy1339 Jan 02 '16 at 18:34
  • I'm not too familiar with JS stuff, but I was under the impression anything in JS works in NodeJS, which is just a framework. A quick google search reveals the Math.random() function in JS, which can do what you're looking for. – Untitled123 Jan 02 '16 at 18:36
  • Yes, anything JavaScript can work with NodeJS. Math.random() only returns numbers between 0 and 1, which isn't what I want – wolfy1339 Jan 02 '16 at 18:38
  • Yes, but the idea is that you can be a bit creative and figure out how to use a random function to get what you need, or post and hope someone will come to the rescue. – Untitled123 Jan 02 '16 at 22:44

2 Answers2

1

For choosing your random characters just do

chars[Math.floor(Math.random() * chars.length)]
Tané Tachyon
  • 1,092
  • 8
  • 11
0

I found my complete answer here: Generating random whole numbers in JavaScript in a specific range?

While the answer provided by @tané-tachyon was good, it wasn't as random as the answer provided on the linked question.

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
Community
  • 1
  • 1
wolfy1339
  • 784
  • 2
  • 7
  • 23