Hello guys, I hope you are having a beautiful day, and if there’s any one of you out there who is coding during the after Christmas day, then Kudos XD.
I need your help. Well, I wrote this beautiful function down here and it’s working pretty well, but I’m afraid my code looks a bit longer and inaccurate than it’s supposed to be.
How can I shrink it? How can I write the same function with less code?
(Here’s the actual task: write a function responsible for randomly selecting a letter in the given array and changing the current letter to a different letter. Then, the function will return the changed letter.
GIVEN ARRAY: const givenArray = [‘A’, ‘T’, ‘C’, ‘G’];
For example, if the randomly selected letter is ‘A’, the letter be changed to ‘T’, ‘C’, or ‘G’. But it cannot be ‘A’ again.) Many many thanks in advance !!!
const changeCode = input => {
newArray = [‘A’, ‘T’, ‘C’, ‘G’];
if(input === ‘A’) {
input = newArray[Math.floor(Math.random()*4)];
if(input === 'A') {
input = newArray[Math.floor(Math.random()*4)];
}
return input;
} else if (a === ‘T’) {
input = newArray[Math.floor(Math.random()*4)];
if(input === 'T') {
input = newArray[Math.floor(Math.random()*4)];
}
return input;
} else if (a === ‘C’) {
input = newArray[Math.floor(Math.random()*4)];
if(input === 'C') {
input = newArray[Math.floor(Math.random()*4)];
}
return input;
} else if (a === ‘G’) {
input = newArray[Math.floor(Math.random()*4)];
if(input === 'G') {
input = newArray[Math.floor(Math.random()*4)];
}
return input;
}
}
let a = ‘T’;
console.log(changeCode(a));