Reputation: 35
I'm replacing all characters in an array with random letters/numbers. However, duplicate letters do not get the same values which is what I want.
var rWords = ["all","ball","balloon"];
var word = rWords[Math.floor(Math.random() * rWords.length)];
var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var getPos = function(arr) {
return Math.floor(Math.random() * arr.length);
}
var arr = word.split('');
for (var i = 0; i < word.length; i++) {
arr.splice(getPos(arr), 1, letters[getPos(letters)]);
}
word = arr.join('');
I want the output to be something like:
all = 4xx, ball = Y4xx, balloon = Y4xxRR1
Upvotes: 1
Views: 149
Reputation: 4066
create a map
function that return unique char for same input (for each character we want to replace we check if we already have a replacement for it stored in _map
, if not then we find one and use it and store it in _map
for future use)
var rWords = ["all","ball","balloon"];
var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var _map = {}
function map(char) {
if (_map[char] === undefined) {
_map[char] = letters[Math.floor(Math.random() * letters.length)]
}
return _map[char]
}
var result = rWords.map(function(word) {
var arr = word.split('');
for (var i = 0; i < word.length; i++) {
arr.splice(i, 1, map(arr[i]));
}
return arr.join('');
})
console.log(result);
Upvotes: 2