I'm trying to write a simple, functional style statement to generate an arbitrary string of a specified length (it does not need to be truly random).
var charSet = '0123456789' +
'ABCDEFGHIJKLMNOPQRSTUVWXZ' +
'abcdefghijklmnopqrstuvwxyz'
// I'm trying for something like:
var randomStringT1 = new Array(10) // I didn't actually expect this to work
.map(v => Math.random())
.map(v => v * (charSet.length - 1))
.map(v => Math.floor(v))
.map(v => charSet.charAt(v))
.join('')
console.log('Take 1: new Array created inline')
console.log('randomStringT1 -->', randomStringT1, '<--')
// However, the `new Array(10)` does not appear to be created to the specified
// length.
// I've also tried creating the array first, e.g.:
var randomStringsArrayT2 = new Array(10) // I did expect this
var randomStringT2 = randomStringsArrayT2 // approach to work
.map(v => Math.random())
.map(v => v * (charSet.length - 1))
.map(v => Math.floor(v))
.map(v => charSet.charAt(v))
.join('')
console.log('Take 2: randomStringsArray from new Array')
console.log('randomStringT2 -->', randomStringT2, '<--')
// But it still returns an empty string.
// The only thing that's worked so far, is to hardcode a new array
// with bogus starter values, like this:
var randomStringArrayT3 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] // !YUCK! !BAD! !EVIL!
var randomStringT3 = randomStringArrayT3
.map(v => Math.random())
.map(v => v * (charSet.length - 1))
.map(v => Math.floor(v))
.map(v => charSet.charAt(v))
.join('')
console.log('Take 3: manually generating a new array with bogus values')
console.log('randomStringT3 -->', randomStringT3, '<--')
// Which does actually result in the desired output, but requires
//
// var randomStringArrayT3 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
//
// !!YUCK!! !!BAD ON TOO MANY LEVELS OF HELL TO COUNT!! !!EVIL!!
Is there a way to generate a new, variable length array in a functional way, i.e. avoiding an explicit loop and hacks like var randomStringArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
?
Edited to add the following.
I also asked a friend offline this question, and his response was:
// Take a symbol set
function string (ss) {
function recurse (len, str) {
// If the count is zero or less, we're done!
if (len <= 0) {
// Base case
return str
}
// Find a random index
var index = Math.floor(Math.random() * ss.length)
// Grab the character
var char = ss[index]
// Recurse! No mutation here!
return recurse(len - 1, str + char)
}
// Return another function which takes the length of the string to generate.
return function (len) {
// No for loop here, we're using immutable recursion!
return recurse(len, '')
}
}
var charSet = '0123456789' +
'ABCDEFGHIJKLMNOPQRSTUVWXZ' +
'abcdefghijklmnopqrstuvwxyz'
var generateString = string(charSet)
console.log(generateString(10));