I started watching the first 2 minutes and really wanted to finish it, but I am going to build it then watch how you did it. I really like how you talk and your style of tutorials, keep it up!
I like these type of videos. It helps to see the entire process. When I first started coding, I was under the impression you must write perfect code from the start when reality, it's all about getting something, literally anything to work first and build upon it. Then, you can refactor and improve the code later. Good job, keep it up!
3:10 if you want to have something fast on the center of the body just do: body { display: flex justify-content: center align-items: center height: 100vh }
Instead of defining the characters used in hex in an array you could have used: function getRandomNumberString(base = 16, length = 6) { const max = Math.pow(base, length) const decimal = Math.floor(Math.random() * max) const hexString = decimal.toString(base).padStart(length, '0') return hexString }
@@captainnoyaux Math.random() gives back like 6-7 bytes back in the mantissa, I multiply the number to get it a bit larger and then cut off the unneeded (shift 32 bits right, so that just introduces zeroes from the right side of the number if represented as binary e.g. 11, 111 >>>2 -> 001)stuff to get the result down to 3 bytes.
I like using rgb() instead of hex for this as well. Would be a very elegant solution with just 3 random values between 0 and 255. Something like this: const r = randomNum(0, 255) const g = randomNum(0, 255) const b = randomNum(0, 255) const color = `rgb(${r},${g},${b})`
You can do something even simpler with HEX. Just convert the color number (base10) to HEX(base16). Something like: const color = randomNum(0, 256**3).toString(16).padStart(6, "0");
at 6:20 where you made an array with the “alphabet” of available characters, you could just put all of them into a string (convert ["a", "b"] into "ab") and use the js split operator to cast it into an array. it ends up with the same outcome but it looks cleaner because its no longer a really long array of characters.
This was great. Hope you do more like this or a more practical "Types of web dev problems you'll most likely come across or be expected to solve/implement" series.
OMG im so happy at first I thought I was not going to be able to do it, but i did it in 25 minutes amazing video and now cant wait to watch the rest of it to see how you did it. This was super fun please do more especiallly so we can practice.
Cool challenge! There's some bad habbits I see in your code. 1. Using useEffect to initialize the state. Just add it as the default value for the state. (only use useEffect if the init state is async). -> useState(() => your init return ) 2. Using arrow functions turns the function also anonymous, so the function name will not come up while debugging. So using the old "function ()" actually will speed up debugging when the project scales.
love that you started by rolling your own solution for generating random numbers. if it works its a solution! made me stick around for the whole tutorial :)
By now I’m pretty strict when in comes to unnecessary useEffect usages. So in an interview with a senior I would have asked the interviewee to refactor it without useEffect.
Before I watch, my initial thought would be: create three buttons. Assign these buttons 3 random hex values to inner text. Put these values into an array. Use math random to choose one of the 3 in the array. Chosen color changes the background style of the colorBox div. Then, if etarget button's inner text === the colorBox div, return success or fail message. Set a timeout to return state to null and then call original function to redo the random selections. An addition I would make would be to have a correct vs wrong score counter that goes up to 10, and returns a % correct choices, to give the user feedback on how well they did overall.
Thanks for this, just did this in an hour and felt really good, even though my answer isn't as elegant as you. I used answerIndexState to randomize the button that display the state, and a colorState object that has the answer and 3 random answer. Like this : function generateColorState() { return { answer: generateRandomColor(), randomOne: generateRandomColor(), randomTwo: generateRandomColor(), randomThree: generateRandomColor(), }; } function generateRandomNumber() { return Math.floor(Math.random() * 3); } // App.jsx const [colorState, setColorState] = useState(generateColorState()); const [answerIndex, setAnswerIndex] = useState(generateRandomNumber()); {answerIndex === 0 ? colorState.answer : colorState.randomOne}
{answerIndex === 2 ? colorState.answer : colorState.randomThree} not as elegant as your solution. but at least i managed to figure this out without stackoverflow :)
Hey, thank you for kinda exercice ! Guessing myself if the correct/wrong logic could be "refactored" in a useEffect ?! will try :) Oh and just, would you put something soft under your keyboard so that isn't any "echo" when you type something ?! It's not crucial but a bit disturbing
I try to use the least amount of useEffect. The clicks should drive your state changes, you shouldn’t use useEffect just to watch for state changes imo
Yeah, you could always ask “is there a better way you’d do this” and they could show you their ability to refactor and keep the code more maintainable. The goal is to see how they problem solve and less about can they solve the problem. For a mid or senior I’d probably ask them to sends their results to a fake api and displays the average score at the end of the test
You did just call a function with "Random()" in it, pure, :D My heart aches :P. A pure functions return value should be determined by only it's arguments (and should have no sideeffects, math.random() breaks both of those). I'd also encode the "NoResult" in the enum.
It’s pure only my in my heart. Yeah this was Non deterministic, I was trying to get at it doesn’t depend on react state or anything inside that compinent
I like this challenge. Simple, but different, and actually produces something of more substance than boring counters and toggles. Though if you wanted to use an effect to set the initial color, you should use `useLayoutEffect` instead in this situation, otherwise you might get a flash for the initial render before the color is set since the component will render twice. Personally I would avoid these effects entirely though by just setting the color as the initial value in `useState`, that would only render once. Another note is that you actually don't even need to randomize the array order, you could just sort it using default alphabetical order. That would still work since you never know which position the actual color is gonna get. Personally when setting optional state value types, I like to just set the type and leave the default empty (this is just a personal preference though). So `useState()` would be the same as `useState(undefined)`. I like your thought process for troubleshooting :) Simple typos can be dreadful. I have more than once set a default value to a variable for testing and then forgotten to remove that after writing to logic for that value, and gotten confused as to why it keeps getting the wrong value.
In an interview context, do you mean the interviewers would want you to live code this in front of them, or give you some time to solve by yourself? I'm at the point where I could make something at this level, but might falter if under short time constraint and scrutiny from the people interviewing. I could talk through my process either way but I'm curious. Great content, thank you!
Another great video, it's great to see the thought process and not just you reimplenting one you did earlier like some do. I do have a question though, how would you make the wrong/correct answer text disappear so that after so many seconds so you can move to next colour without it already been there.
1) You can use a string of chars instead of an array...js can iterate over it with charAt 2) no need for state of validation...onClick check if value is right then render proper message. 3) setWrongColor(value===currColor)...avoid verbose Boolean statements. 4)migrating pickcolor...mind the scoping...this is semantic but mind the scope...make it an import or keep in component if it only serves it. 5) note the button wrapper exceeds the width of the color div on occasion...css should factor max content
Nice video but this whole getRandomColor function could just be written like this: return `#${Math.floor(Math.random() * (16 ** 6)).toString(16).padStart(6, '0')}` Hex is base 16, there are 6 hex chars in the color definition, so 16 ^ 6 should give us all the possible colors there can be. Generate the random number, floor it, cast it to string, add the zeroes in the beginning to make sure the code is correct. Hard-coding this stuff is good as well, the viewer actually can understand how the algorithm works, but it is not an efficient way to write code. Also, as mentioned, the alphabet can be made like this: "01234567890abcdef".split()
Nice tiny solution. Will it be then more statistically probable, that left bytes will be a zero? Also 0xffffff looks little bit more sexy than (16 ** 6 - 1).
@@JanVotava The statistical probability of first numbers being 0 is the same, however, I made a little mistake. The reason is Math.floor, which will never let us reach the max value of 0xFFFFFF, so instead it should be 0xFFFFFF + 1, or 16**6 instead of 16**6 - 1. Writing in Hex is indeed cleaner but I wanted to demonstrate the logic behind the numbers
For generating a hex, I think the way you did it might be how a Jr dev would do it. However, I think the most cleanest way is as follows: function getRandomHex() { const red = parseInt(Math.random() * 255); const green = parseInt(Math.random() * 255); const blue = parseInt(Math.random() * 255); return `#{red.toString(16)}{green.toString(16)}{blue.toString(16)}`; }
That looks nice as well! There are many ways to generate a hex string so it would be interesting to watch how someone else solves it during an interview. I wouldn’t expect a beginner to remember toString on a number has a radix param
@@WebDevCody I wouldn't either. That said, even if they didn't know the exact syntax, for me it is more about the concept of converting from decimal to hex that is important. For me, I'd rather someone who maybe knows a tad less (Because we are kidding ourselves if even as mid and senior levels engineers, we aren't using stackoverflow and google.)but is resourceful than someone who knows a lot but can't figure out how to google their error and fix it.
Yeah if they allow you to google for a solution then you should find something on stack overflow. Sometimes the interview is purposely trying to test how you problem solve with the knowledge you current have
I hesitated to do this before watching because I thought I wouldn't be able to even as working as a grad dev lmao. But I managed to do it and only looked up the hex value generation so a bit of honest copium there as I had no clue otherwise. But other than that, a nice challenge. Also centering a div in vanilla css is surprisingly difficult and made me realise using css libraries is a crutch that I gotta work on/get rid of. Nice vid mayn
The flex approach is the way to center, quite simple. The potentially complicated part is knowing how "height:100%" works, because it's not the same as "width:100%". I would probably use "height:100vh" instead though, that way I wouldn't have to style all the parent elements. 100vh is "100% of the viewport height", whereas normal percent is 100% of the parent height (all of which normally shrink to fit the content).
Should probably handle the case where the random generated strings overlap with other answers. Chances are low but it would be bonus point especially when you’re junior.
Hi, thanks for the videos. I had one more question where we need to build a soccer score board with API. they where looking for automatic refresh scenarios too. Can you solve it and upload a video please.
Would a demo like this be conducted live or would this be like a take home kinda project to finish during the day? Just starting to prep for interviews.
I'd like to know as well! I kind of stumbled on a couple of steps here (couldn't center the div for a while, then played with the dec->hex function...), so I feel like at this point I wouldn't be fast enough for this to be conducted live (and without some googling e.g. for the css), even though I wanted to start applying for junior dev positions :'/.
Don’t let it discourage you. This was just one example, some interviews will be easier and others harder. If you instead made this into a math game instead of hex, could you solve it?
Great video, WDJ! Your videos provide great how-to’s and tips in real life coding scenarios. Thank you! What type of intellisense extensions do you use? Have you posted a video on this?
Yes, that’s what I said I thought? This was a simple front end challenge for a junior position that would rise some red flags if someone couldn’t at least get most of the way through this challenge.
Cool video to show of how to use react. I never used it. But I don't generally like how you'd introduce dependencies for whatever you need such as shuffling etc. Generating a color could be simplified to a simple math.random() call. Color is a hex 3 byte number. Which means it ranges from 0 to 2^24, meaning colour is in range of 0 to 16777216 (including 0, which is pure black). So you just generate random number in that range and parse to hex string. Easy as that.
For generating a random single character, would the pseudocode below be considered better than explicitly defining the list - Generating a number between 0-15 (including 0 and 15 ofc) Checking whether the number was greater than or equal to 10 if greater - const min = 55; // 10 less than capital A return String.charcodeat(min + generated) else if less - return generated.toString() Or would it generally be considered too convoluted?
@@WebDevCody Yeah, it does look more convoluted when written out. I just figured the explanation of "uses the number of it's 0-9 or the letter if it's above that" was simpler in theory.
If I built this without looking and without stackoverflow, should I start applying to jr roles? Like is this a solid indicator that I am competent enough for a jr role?
I’d say closer to yes if you didn’t have much issue making this within 30 min or an hour with no help. You’d still need to be able to answer some other technical and personality type questions, but it’s a good sign you’re learning
const genRanHex = (size: number) => [...Array(size)] .map(() => Math.floor(Math.random() * 16).toString(16)) .join(""); genRanHex(6); /* * Here is an explanation of each step: ^ 1.[...Array(size)] creates a new empty array with "size" number of elements. ^ 2. .map(...) applies a function to each element of the array created in step 1. The function inside map() is an arrow function which does the following: ! 1. Math.floor(Math.random() * 16) generates a random number between 0 and 15. ! 2. .toString(16) converts the random number to a hexadecimal string. ^ 3. .join("") joins all elements of the array created in step 2, into a single string. ? So the final output is a random hexadecimal string with the length of the input size. */
I am confused about one thing here, in generate colors u call setColor and then setAnswers, problem for me is that it seems that it takes some time to get the color so when setAnswers is called color has not been set yet, so setAnswers is called with actual color being undefined, i solved it by using useEffect but how come it works with yours.
@@WebDevCody After looking into it, i am not sure if typescript prevents this, but setState is asynchronous so when setanswers is called the random color we picked is still undefined which causes problems, so the solution to that is to ether use useEffect or use one setState and combine the two states into one, both ways fixed my problem.
@@XbattlepopeX The semi-solution in this coding example is to generate the new 'correct' color first as a variable and pass that into both setState calls. If you're trying to grab the current 'correct' color inside the generate random 3 generate logic, the state won't be updated in time. (Also ran into this problem) -- Coming from Angular, this confused me a bit, and feels like a duct-tape fix, but it works.
Maybe or maybe not. there would be more context to the interview. If they couldn’t figure out the hex, I’d change the problem a to instead show two numbers and a plus symbol and they need to guess the correct sum. It’s the same idea but a bit easier than expecting them to know hex. I’m not trying to be a gate keeper, but this is a super simple application. If I’m going to pay someone, they need to know how to build basic things and problem solve.
Really? A simple quiz app? Idk man, as a junior you should be able to build this pretty easily. I didn’t watch the whole video but I saw other comments implying he said you should memorize hex. That’s not true, we have google for a reason
@@Benjamin-ud2xe I don’t recall ever saying memorize hex. That’s dumb. The challenge is related to hex and knowing the three parts of hex and that characters that make if up, that’s about it
@@WebDevCody ah ok apologies, I was just reading other comments. I didn’t watch the whole thing. Then yes Mr Gains you should be able to do this whole project as a junior! If you can’t then this video is a good starting point.
@@Benjamin-ud2xe not really. I am a junior in a SaaS company and I wouldn't be able to make this on the spot without help. I am more than capable of the simple tasks I am getting at my job to get me up to speed, however...
Few years a go I did a clor flipper and the way I generated a random color was this let randomColor = Math.floor(Math.random()*16777215).toString(16); Then you just need to concat '#' infront and you are good to go. But as you said you, you never get the best solution at the moment. This is how it is. Good job and interesting task I would say! :)
This is fine as long as it isn't expected to be done live. A bit on the extreme end imo, maybe someone with .5-1 yr of experience or something like that.
One thing that annoys me is "take home" tests. Losing time I could be using on applications or other companies. Need to pay me to do it or pass on me. I don't do them at all.
This is such an odd thing to make in react. This could easily be made in pure JS, HTML, and CSS. I just did it in fact and it was pretty easy. Obviously this is easier in React, but it seems excessive to use a framework.
@@WebDevCody my latest job they asked me to build a simple JavaScript calculator in react. I only had 20 minutes so it was just a very basic addition subtraction calculator. In my previous ones I was given an object of arrays. And was asked to do some conditional logic to get specific data. Like get all users from 1995 to the year 2000 that are over 25 years old and is below the height of 5'5.... Something like that
I like this challenge for a junior developtment, I would appreciated more if the junior dev would be able to identify what elements could be wrapped into a new component because that would mean they are able to identify differents element and how to separate responsabilities and make components more testeasble and reusables.
LMFAOOOO, a JUNIOR web dev should be able to do this?! Holy shit bruh...i'm 10 yrs in and I'd need to Google or stack overflow this, if i had to live code it? it'd be over for me. Guess i AM a bad developer :-(
I’m not misleading anyone. Hex isn’t some advanced concept; most beginner css courses will cover coloring with hex. This challenge tests if you can figure out how to build up hex strings and use them to style react jsx. Pretty basic
To avoid multiple generateColors calls, I suggest to use the useEffect hook this way (sorry for my english :) ): const [color, setColor] = useState(undefined); const [result, setResult] = useState(undefined); useEffect(() => { if(result === Result.WRONG) return; generateColors(); }, [result]); const handleAnswerClicked = (answer) => { setResult(answer === color ? Result.CORRECT : Result.WRONG); }
Actually this(for me) is cool and easy task. I jusy have done few recruitment project and one of them was to create full stack app, which I have done. Still rejected 😂
If this guy is a 'senior webdeveloper' then we can all make it. What a fool, can't even center a div :D He wouldn't pass a interview in any of the big companies.
You really need to brush up on your CSS, friend. So many times you could've used a (much) better solution (just setting min-height on the wrapper, using flexbox or grid, etc.) and I just see you struggle to align things by hard-coding it.
Agreed, I work a lot more in the backend, devops, and react logic side of things, I don’t need to touch css often since my project at work uses an existing design system
I built out this project on my own prior to finishing the video. I stopped at the part after I understood what the question was. I then compared your final result with mine and ended up fairly similar. I didn't use typescript. I ended up building a custom hook to generate the color and abstracted out all the setup for color randomization. Since I didn't start with typescript I ended up having to use another state variable for if it was a new color to fix it rendering the "wrong" state on load. Overall great video. Love your thought process and how you tackle certain things. One main difference I noticed is i used a 1 liner to generate the random hex instead of the array you created. `#${Math.floor(Math.random() * 16777215).toString(16)}`
I’m glad you tried to follow along! Did you google that one liner or did you just do a bunch of math to figure out the max value of rgb hex? I guess we could also do 0xFFFFFF * Math.random(). I think js supports that if I remember correctly
@@WebDevCody I did Google it. I just figured it's what Id do at my job currently. I'm sure I could figure it out after a ton of math. I can't say that I would have came up with your solution on the fly like you did. Hats off to you for being able to do that that quickly
I started watching the first 2 minutes and really wanted to finish it, but I am going to build it then watch how you did it. I really like how you talk and your style of tutorials, keep it up!
I like these type of videos. It helps to see the entire process. When I first started coding, I was under the impression you must write perfect code from the start when reality, it's all about getting something, literally anything to work first and build upon it. Then, you can refactor and improve the code later. Good job, keep it up!
Make it work, make it right, make it fast
i agree i love the way his process is in a vulnerable way
Keep these kinds of videos coming, they are extremely informative and enjoyable!
3:10 if you want to have something fast on the center of the body just do:
body {
display: flex
justify-content: center
align-items: center
height: 100vh
}
Hexadecimal colors a red flag for Jr developers? Yikes. I'd say maybe a red flag for Jr designers not devs.
3 yoe hex colors required for jr
What’s your question? Im saying a junior web dev should be able to build this or figure it out
@@WebDevCody he's joking
@@rkjj. I’m not sure he is
I think he means if you can't build this then it's a red flag.
Instead of defining the characters used in hex in an array you could have used:
function getRandomNumberString(base = 16, length = 6) {
const max = Math.pow(base, length)
const decimal = Math.floor(Math.random() * max)
const hexString = decimal.toString(base).padStart(length, '0')
return hexString
}
(Math.random()*0xffffff>>>32).toString(16) if you wanna keep it a oneliner
ok nerd
@@smiche2 thank you, I hate it 🤣(but I steal that anyway ) why do you shift to the right 32 times ?
@@captainnoyaux Math.random() gives back like 6-7 bytes back in the mantissa, I multiply the number to get it a bit larger and then cut off the unneeded (shift 32 bits right, so that just introduces zeroes from the right side of the number if represented as binary e.g. 11, 111 >>>2 -> 001)stuff to get the result down to 3 bytes.
I was able to do this within 15 minutes and I'm so proud of myself. This is month 3 of learning react and its so much fun
I find that hard to believe. but good for you lol. how long have you been programming?
@@BobbyBundlez it's not that hard to do, especially with 3 months of practice
@@hasaniqbal233 yeah I figured it out quite easily after one watch
@@BobbyBundlez I didn't even watch it and I was able to get it ;) lol
I like using rgb() instead of hex for this as well.
Would be a very elegant solution with just 3 random values between 0 and 255. Something like this:
const r = randomNum(0, 255)
const g = randomNum(0, 255)
const b = randomNum(0, 255)
const color = `rgb(${r},${g},${b})`
You can do something even simpler with HEX. Just convert the color number (base10) to HEX(base16).
Something like:
const color = randomNum(0, 256**3).toString(16).padStart(6, "0");
@@sael40 ah yes so much simpler
at 6:20 where you made an array with the “alphabet” of available characters, you could just put all of them into a string (convert ["a", "b"] into "ab") and use the js split operator to cast it into an array. it ends up with the same outcome but it looks cleaner because its no longer a really long array of characters.
That would have been a lot simpler for sure!
Or he could just generate three random numbers, convert them to hex and join them together.
Fresh project is amazing to watch and follow till the end
I was asked to make a similar kind of game few weeks ago . Its indeed very common.
It is very challenging and helpful to master your logics and fundamentals, keep them coming ! doing a great job .
This was great. Hope you do more like this or a more practical "Types of web dev problems you'll most likely come across or be expected to solve/implement" series.
OMG im so happy at first I thought I was not going to be able to do it, but i did it in 25 minutes amazing video and now cant wait to watch the rest of it to see how you did it. This was super fun please do more especiallly so we can practice.
Cool challenge!
There's some bad habbits I see in your code.
1. Using useEffect to initialize the state. Just add it as the default value for the state. (only use useEffect if the init state is async).
-> useState(() => your init return )
2. Using arrow functions turns the function also anonymous, so the function name will not come up while debugging. So using the old "function ()" actually will speed up debugging when the project scales.
Factually wrong. Arrow functions receive the name of the variable they were assigned to at creation time.
@@voidedname Thanks. And you're correct :) I learned something new.
love that you started by rolling your own solution for generating random numbers. if it works its a solution! made me stick around for the whole tutorial :)
You're really cool dude. Awesome,how to explain more detail about code and refactoring your code. 🎉
Company hr: build a facebook app in 30mins
Really like your videos. Keep it up!
"If a junior can't do this, it's a red flag"
6:23: "Let me manually type a random numbers array" :D
Solving the problem is solving the problem 😉
Nice. Enjoyed this challenge alot.
By now I’m pretty strict when in comes to unnecessary useEffect usages. So in an interview with a senior I would have asked the interviewee to refactor it without useEffect.
Before I watch, my initial thought would be: create three buttons. Assign these buttons 3 random hex values to inner text. Put these values into an array. Use math random to choose one of the 3 in the array. Chosen color changes the background style of the colorBox div. Then, if etarget button's inner text === the colorBox div, return success or fail message. Set a timeout to return state to null and then call original function to redo the random selections.
An addition I would make would be to have a correct vs wrong score counter that goes up to 10, and returns a % correct choices, to give the user feedback on how well they did overall.
That is a possible solutions
These challenges are gold 💯
love this kind of video
When he tried setting the height of the page , too real man....
Thanks for this, just did this in an hour and felt really good, even though my answer isn't as elegant as you. I used answerIndexState to randomize the button that display the state, and a colorState object that has the answer and 3 random answer. Like this :
function generateColorState() {
return {
answer: generateRandomColor(),
randomOne: generateRandomColor(),
randomTwo: generateRandomColor(),
randomThree: generateRandomColor(),
};
}
function generateRandomNumber() {
return Math.floor(Math.random() * 3);
}
// App.jsx
const [colorState, setColorState] = useState(generateColorState());
const [answerIndex, setAnswerIndex] = useState(generateRandomNumber());
{answerIndex === 0 ? colorState.answer : colorState.randomOne}
{answerIndex === 1 ? colorState.answer : colorState.randomTwo}
{answerIndex === 2 ? colorState.answer : colorState.randomThree}
not as elegant as your solution. but at least i managed to figure this out without stackoverflow :)
Hey, thank you for kinda exercice !
Guessing myself if the correct/wrong logic could be "refactored" in a useEffect ?! will try :)
Oh and just, would you put something soft under your keyboard so that isn't any "echo" when you type something ?! It's not crucial but a bit disturbing
I try to use the least amount of useEffect. The clicks should drive your state changes, you shouldn’t use useEffect just to watch for state changes imo
@@WebDevCody Yep, you're definitely right, let's keep thing at what they do best.
And thank you for the useState syntax i didn't knew
i would ask simikar question to mid-senior devs too and check how they manage the code and how long it takes them to finish it
Yeah, you could always ask “is there a better way you’d do this” and they could show you their ability to refactor and keep the code more maintainable. The goal is to see how they problem solve and less about can they solve the problem. For a mid or senior I’d probably ask them to sends their results to a fake api and displays the average score at the end of the test
You did just call a function with "Random()" in it, pure, :D My heart aches :P. A pure functions return value should be determined by only it's arguments (and should have no sideeffects, math.random() breaks both of those).
I'd also encode the "NoResult" in the enum.
It’s pure only my in my heart. Yeah this was Non deterministic, I was trying to get at it doesn’t depend on react state or anything inside that compinent
@@WebDevCody I know, or at least assumed that's what you meant. Couldn't resist though
I like this challenge. Simple, but different, and actually produces something of more substance than boring counters and toggles.
Though if you wanted to use an effect to set the initial color, you should use `useLayoutEffect` instead in this situation, otherwise you might get a flash for the initial render before the color is set since the component will render twice. Personally I would avoid these effects entirely though by just setting the color as the initial value in `useState`, that would only render once.
Another note is that you actually don't even need to randomize the array order, you could just sort it using default alphabetical order. That would still work since you never know which position the actual color is gonna get.
Personally when setting optional state value types, I like to just set the type and leave the default empty (this is just a personal preference though). So `useState()` would be the same as `useState(undefined)`.
I like your thought process for troubleshooting :) Simple typos can be dreadful. I have more than once set a default value to a variable for testing and then forgotten to remove that after writing to logic for that value, and gotten confused as to why it keeps getting the wrong value.
Lots of good insight here in this comment, thanks for posting it
I actually did this challenge, probably not the best code...but i did it. Thanks for the video, i like a new challenge.
In an interview context, do you mean the interviewers would want you to live code this in front of them, or give you some time to solve by yourself? I'm at the point where I could make something at this level, but might falter if under short time constraint and scrutiny from the people interviewing. I could talk through my process either way but I'm curious. Great content, thank you!
I was thinking it would be a live code session maybe an hour max, and the person could help answer questions or provide guidance if totally lost
@@WebDevCody that makes sense, I could probably do it or at least talk through it even if my code wasn't perfect. Thanks for the motivation!
@@stevebob240 yeah solving the problem isn’t as important as seeing how they go about trying to solve the problem
@@WebDevCody is google allowed in these type of interviews? like for the get hexstring for example..?
Another great video, it's great to see the thought process and not just you reimplenting one you did earlier like some do.
I do have a question though, how would you make the wrong/correct answer text disappear so that after so many seconds so you can move to next colour without it already been there.
Probably a setTimeout and change the result state back to null after 2 seconds
Great Challenge for junior
1) You can use a string of chars instead of an array...js can iterate over it with charAt
2) no need for state of validation...onClick check if value is right then render proper message.
3) setWrongColor(value===currColor)...avoid verbose Boolean statements.
4)migrating pickcolor...mind the scoping...this is semantic but mind the scope...make it an import or keep in component if it only serves it.
5) note the button wrapper exceeds the width of the color div on occasion...css should factor max content
Nice video but this whole getRandomColor function could just be written like this:
return `#${Math.floor(Math.random() * (16 ** 6)).toString(16).padStart(6, '0')}`
Hex is base 16, there are 6 hex chars in the color definition, so 16 ^ 6 should give us all the possible colors there can be. Generate the random number, floor it, cast it to string, add the zeroes in the beginning to make sure the code is correct. Hard-coding this stuff is good as well, the viewer actually can understand how the algorithm works, but it is not an efficient way to write code. Also, as mentioned, the alphabet can be made like this: "01234567890abcdef".split()
Nice tiny solution. Will it be then more statistically probable, that left bytes will be a zero? Also 0xffffff looks little bit more sexy than (16 ** 6 - 1).
@@JanVotava The statistical probability of first numbers being 0 is the same, however, I made a little mistake. The reason is Math.floor, which will never let us reach the max value of 0xFFFFFF, so instead it should be 0xFFFFFF + 1, or 16**6 instead of 16**6 - 1. Writing in Hex is indeed cleaner but I wanted to demonstrate the logic behind the numbers
I think you need to padStart every component (r,g,b) separately, otherwise you get more bluish colors when you add all zeroes to the left.
For generating a hex, I think the way you did it might be how a Jr dev would do it.
However, I think the most cleanest way is as follows:
function getRandomHex() {
const red = parseInt(Math.random() * 255);
const green = parseInt(Math.random() * 255);
const blue = parseInt(Math.random() * 255);
return `#{red.toString(16)}{green.toString(16)}{blue.toString(16)}`;
}
That looks nice as well! There are many ways to generate a hex string so it would be interesting to watch how someone else solves it during an interview. I wouldn’t expect a beginner to remember toString on a number has a radix param
@@WebDevCody I wouldn't either. That said, even if they didn't know the exact syntax, for me it is more about the concept of converting from decimal to hex that is important.
For me, I'd rather someone who maybe knows a tad less (Because we are kidding ourselves if even as mid and senior levels engineers, we aren't using stackoverflow and google.)but is resourceful than someone who knows a lot but can't figure out how to google their error and fix it.
Didn't know CaptainSparklez was so good at coding
the best junkie developer i ever seen in my entire life 🗿👌 thanks for video
I’d say a red flag would be trying to reinvent how to generate a random hex color instead of searching for the best existing solution first.
Yeah if they allow you to google for a solution then you should find something on stack overflow. Sometimes the interview is purposely trying to test how you problem solve with the knowledge you current have
19:00 Why not
{result && a || b}
Try it and let me know if it works
I hesitated to do this before watching because I thought I wouldn't be able to even as working as a grad dev lmao. But I managed to do it and only looked up the hex value generation so a bit of honest copium there as I had no clue otherwise. But other than that, a nice challenge. Also centering a div in vanilla css is surprisingly difficult and made me realise using css libraries is a crutch that I gotta work on/get rid of. Nice vid mayn
The flex approach is the way to center, quite simple. The potentially complicated part is knowing how "height:100%" works, because it's not the same as "width:100%". I would probably use "height:100vh" instead though, that way I wouldn't have to style all the parent elements. 100vh is "100% of the viewport height", whereas normal percent is 100% of the parent height (all of which normally shrink to fit the content).
Should probably handle the case where the random generated strings overlap with other answers. Chances are low but it would be bonus point especially when you’re junior.
Could use a set and while(set.size < 3) set.add(getRandomColor) ?
parseInt only takes string arguments. Good video I loved it
Hi, thanks for the videos. I had one more question where we need to build a soccer score board with API. they where looking for automatic refresh scenarios too. Can you solve it and upload a video please.
Hi, where you able to solve it
Would a demo like this be conducted live or would this be like a take home kinda project to finish during the day? Just starting to prep for interviews.
This would be a live challenge you’d do in front of someone. They’d be there to maybe give you some hints if you got stuck or confused
I'd like to know as well! I kind of stumbled on a couple of steps here (couldn't center the div for a while, then played with the dec->hex function...), so I feel like at this point I wouldn't be fast enough for this to be conducted live (and without some googling e.g. for the css), even though I wanted to start applying for junior dev positions :'/.
Don’t let it discourage you. This was just one example, some interviews will be easier and others harder. If you instead made this into a math game instead of hex, could you solve it?
Great video, WDJ! Your videos provide great how-to’s and tips in real life coding scenarios. Thank you!
What type of intellisense extensions do you use? Have you posted a video on this?
Just typescript built into vscode
Do you use some extension to get error message in-line with the code? Or is just typescript? Thanks! Great video
which do you use visual studio theme?
I thought the red flag is not able to build this, no guessing the actual color
Yes, that’s what I said I thought? This was a simple front end challenge for a junior position that would rise some red flags if someone couldn’t at least get most of the way through this challenge.
Why would you need to know hex color by heart ? Aside from a few standard colors just so you can test things real quick.
You don’t
Cool video to show of how to use react. I never used it. But I don't generally like how you'd introduce dependencies for whatever you need such as shuffling etc.
Generating a color could be simplified to a simple math.random() call.
Color is a hex 3 byte number. Which means it ranges from 0 to 2^24, meaning colour is in range of 0 to 16777216 (including 0, which is pure black). So you just generate random number in that range and parse to hex string. Easy as that.
Yup that works as well, but I wouldn’t expect a junior to know all that
For generating a random single character, would the pseudocode below be considered better than explicitly defining the list -
Generating a number between 0-15 (including 0 and 15 ofc)
Checking whether the number was greater than or equal to 10
if greater -
const min = 55; // 10 less than capital A
return String.charcodeat(min + generated)
else if less -
return generated.toString()
Or would it generally be considered too convoluted?
Sounds a lot more convoluted
@@WebDevCody Yeah, it does look more convoluted when written out.
I just figured the explanation of "uses the number of it's 0-9 or the letter if it's above that" was simpler in theory.
how is he getting errors display inline like that
Instead of creating enum, you could just store selected color and compare it to the generated one.
This is awesome
Whats the extention where it says something expected when typing code?
Typescript
@@WebDevCody oh ok im still learning vinalla js thanks for replying love the videos
Are you allowed to be FE developer if your right button is not aligned with a right side of a color block?
Nope
If I built this without looking and without stackoverflow, should I start applying to jr roles? Like is this a solid indicator that I am competent enough for a jr role?
I’d say closer to yes if you didn’t have much issue making this within 30 min or an hour with no help. You’d still need to be able to answer some other technical and personality type questions, but it’s a good sign you’re learning
Thank you for the reply! Your response motivates me even further.
Now, on to your async/await and promises videos!
const genRanHex = (size: number) =>
[...Array(size)]
.map(() => Math.floor(Math.random() * 16).toString(16))
.join("");
genRanHex(6);
/*
* Here is an explanation of each step:
^ 1.[...Array(size)] creates a new empty array with "size" number of elements.
^ 2. .map(...) applies a function to each element of the array created in step 1. The function inside map() is an arrow function which does the following:
! 1. Math.floor(Math.random() * 16) generates a random number between 0 and 15.
! 2. .toString(16) converts the random number to a hexadecimal string.
^ 3. .join("") joins all elements of the array created in step 2, into a single string.
? So the final output is a random hexadecimal string with the length of the input size.
*/
I am confused about one thing here, in generate colors u call setColor and then setAnswers, problem for me is that it seems that it takes some time to get the color so when setAnswers is called color has not been set yet, so setAnswers is called with actual color being undefined, i solved it by using useEffect but how come it works with yours.
I’d have to see your code. There must be some typos somewhere
@@WebDevCody cant share links here for reactplayground but i send it through mail if u still interested to look at it.
@@WebDevCody After looking into it, i am not sure if typescript prevents this, but setState is asynchronous so when setanswers is called the random color we picked is still undefined which causes problems, so the solution to that is to ether use useEffect or use one setState and combine the two states into one, both ways fixed my problem.
@@XbattlepopeX The semi-solution in this coding example is to generate the new 'correct' color first as a variable and pass that into both setState calls. If you're trying to grab the current 'correct' color inside the generate random 3 generate logic, the state won't be updated in time. (Also ran into this problem) -- Coming from Angular, this confused me a bit, and feels like a duct-tape fix, but it works.
I was able to do this in about an hour. Would that be an acceptable timeframe?
Yeah I think so, most technical interviews might be an hour max and the interviewer would sometimes give hints along the way if needed
Do you have a patreon?
Yeah should be in the description
That’s all you need to be able to do, for a junior Dev position?
No, that would be just one part of the interview
I think your expectations for a junior are quite high if it's a red flag when the person is not able to make a game like that on the spot.
Maybe or maybe not. there would be more context to the interview. If they couldn’t figure out the hex, I’d change the problem a to instead show two numbers and a plus symbol and they need to guess the correct sum. It’s the same idea but a bit easier than expecting them to know hex. I’m not trying to be a gate keeper, but this is a super simple application. If I’m going to pay someone, they need to know how to build basic things and problem solve.
Really? A simple quiz app? Idk man, as a junior you should be able to build this pretty easily. I didn’t watch the whole video but I saw other comments implying he said you should memorize hex. That’s not true, we have google for a reason
@@Benjamin-ud2xe I don’t recall ever saying memorize hex. That’s dumb. The challenge is related to hex and knowing the three parts of hex and that characters that make if up, that’s about it
@@WebDevCody ah ok apologies, I was just reading other comments. I didn’t watch the whole thing. Then yes Mr Gains you should be able to do this whole project as a junior! If you can’t then this video is a good starting point.
@@Benjamin-ud2xe not really. I am a junior in a SaaS company and I wouldn't be able to make this on the spot without help. I am more than capable of the simple tasks I am getting at my job to get me up to speed, however...
Few years a go I did a clor flipper and the way I generated a random color was this
let randomColor = Math.floor(Math.random()*16777215).toString(16);
Then you just need to concat '#' infront and you are good to go.
But as you said you, you never get the best solution at the moment. This is how it is. Good job and interesting task I would say! :)
This is fine as long as it isn't expected to be done live. A bit on the extreme end imo, maybe someone with .5-1 yr of experience or something like that.
nice vid!
One thing that annoys me is "take home" tests. Losing time I could be using on applications or other companies. Need to pay me to do it or pass on me. I don't do them at all.
This is such an odd thing to make in react. This could easily be made in pure JS, HTML, and CSS.
I just did it in fact and it was pretty easy. Obviously this is easier in React, but it seems excessive to use a framework.
Sure, but this isn’t a vanilla js interview question lol
"if they couldn't do it it would be a red flag", struggles to center div 🤣
The hardest thing in web dev
@@WebDevCody couldn't agree more :)
"Red flag for junior developers"... Man can't even center a div.
This is way to advanced for a junior dev position
I disagree
@@WebDevCody I've been through four technical interviews. This would be the hardest question I would have received. My first job was in 2018.
@@alexlytle089 what did they ask you to do / build?
@@WebDevCody my latest job they asked me to build a simple JavaScript calculator in react. I only had 20 minutes so it was just a very basic addition subtraction calculator. In my previous ones I was given an object of arrays. And was asked to do some conditional logic to get specific data. Like get all users from 1995 to the year 2000 that are over 25 years old and is below the height of 5'5.... Something like that
@@WebDevCody other ones I've had to solve a toy problem like find first unique character in a string. Group anagrams.. reverse a string
Commenting using adept experiments
Good job babe!!!
If you can center a div first try I think you should get the job.
FD not a colorvalue
okay it is one my bad
I like this challenge for a junior developtment, I would appreciated more if the junior dev would be able to identify what elements could be wrapped into a new component because that would mean they are able to identify differents element and how to separate responsabilities and make components more testeasble and reusables.
You shouldn't use margins to position elements or act as padding. Rather use flexbox gap for the bottom buttons. Would have failed you for that ;)
Gap is good, idk if failing someone because they used margin for a junior position is a smart move, but you do you
@@WebDevCody was joking about the fail part
@@michaelcohen7676 ah ok 😂 it’s hard to know if people are trolling or serious in comments these days
neat.
LMFAOOOO, a JUNIOR web dev should be able to do this?! Holy shit bruh...i'm 10 yrs in and I'd need to Google or stack overflow this, if i had to live code it? it'd be over for me. Guess i AM a bad developer :-(
You can’t show 3 buttons on a screen and randomly generate colors after 10 years of coding?
You don't have to cramp hexa codes, please don't mislead new learners
I’m not misleading anyone. Hex isn’t some advanced concept; most beginner css courses will cover coloring with hex. This challenge tests if you can figure out how to build up hex strings and use them to style react jsx. Pretty basic
he's not talking about learning the actual hex codes, but building this little game.
To avoid multiple generateColors calls, I suggest to use the useEffect hook this way (sorry for my english :) ):
const [color, setColor] = useState(undefined);
const [result, setResult] = useState(undefined);
useEffect(() => {
if(result === Result.WRONG) return;
generateColors();
}, [result]);
const handleAnswerClicked = (answer) => {
setResult(answer === color ? Result.CORRECT : Result.WRONG);
}
Good work! ps: react is so unatractive to me...
This is perfect, but now the applicant can just find this video and cheat. 😂
You’re welcome
3:10 red flag xD
Lol you know it, but I still solved the problem 🤯
This sort as a shuffle is so messy.
This is impractical when vs lets you know what color you are picking with extensions, Other than an interview test I don't see the point of this.
Read the title, then read your comment. What do you think the point of this challenge is for?
Cool
OMG you got rejected at minute 3
Lol
Actually this(for me) is cool and easy task. I jusy have done few recruitment project and one of them was to create full stack app, which I have done. Still rejected 😂
If this guy is a 'senior webdeveloper' then we can all make it. What a fool, can't even center a div :D He wouldn't pass a interview in any of the big companies.
Did that make you feel better about yourself?
Ngawww someone bring this person some warm milk.
You really need to brush up on your CSS, friend. So many times you could've used a (much) better solution (just setting min-height on the wrapper, using flexbox or grid, etc.) and I just see you struggle to align things by hard-coding it.
Agreed, I work a lot more in the backend, devops, and react logic side of things, I don’t need to touch css often since my project at work uses an existing design system
Looks like a fun exercise, keep making video's like this 👍 but tbh HSL is better and easier to work with
Cancel in-person coding interviews
That’s so easy it’s ridiculous
Nice clickbait
How is this click bait? 😂
lmao webdevs are a joke
Why’s that?
I built out this project on my own prior to finishing the video. I stopped at the part after I understood what the question was. I then compared your final result with mine and ended up fairly similar. I didn't use typescript. I ended up building a custom hook to generate the color and abstracted out all the setup for color randomization. Since I didn't start with typescript I ended up having to use another state variable for if it was a new color to fix it rendering the "wrong" state on load. Overall great video. Love your thought process and how you tackle certain things. One main difference I noticed is i used a 1 liner to generate the random hex instead of the array you created. `#${Math.floor(Math.random() * 16777215).toString(16)}`
I’m glad you tried to follow along! Did you google that one liner or did you just do a bunch of math to figure out the max value of rgb hex? I guess we could also do 0xFFFFFF * Math.random(). I think js supports that if I remember correctly
@@WebDevCody I did Google it. I just figured it's what Id do at my job currently. I'm sure I could figure it out after a ton of math. I can't say that I would have came up with your solution on the fly like you did. Hats off to you for being able to do that that quickly