Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
paulscanlon
Courses Plus Student 26,735 PointsRandom Number generator
Hi guys
I've made a random colour generator for something that I'm working on. Is there any way I can get the same result without repeating the first three lines.
function randomColour () {
let r = Math.floor( Math.random() * (255 - 0) + 1 );
let g = Math.floor( Math.random() * (255 - 0) + 1 );
let b = Math.floor( Math.random() * (255 - 0) + 1 );
let result = `rgb(${r},${g},${b})`;
return result;
}
Is there any way I can compact those three variables so they each get a different random number?
Thanks in advance
Paul
1 Answer
Steven Parker
243,656 PointsYou could always make another function and call it from this one. And you don't need to shift the range since 0 is a valid color component value:
var cv = () => Math.floor( Math.random() * 256 );
var randomColour = () => `rgb(${cv()},${cv()},${cv()})`;
paulscanlon
Courses Plus Student 26,735 Pointspaulscanlon
Courses Plus Student 26,735 PointsHey thanks Steven, it only works if I change the second line to a variable, not a function.
let result = `rgb(${rand()},${rand()},${rand()})`;It works, now anyway. Thanks man
Paul
paulscanlon
Courses Plus Student 26,735 Pointspaulscanlon
Courses Plus Student 26,735 PointsJust realised I was returning without the parethesis.....ignore me!