Skip to content

Instantly share code, notes, and snippets.

@CodeSigils
Last active October 19, 2016 15:40
Show Gist options
  • Save CodeSigils/ab901c00c916b0431082db992dd5e194 to your computer and use it in GitHub Desktop.
Save CodeSigils/ab901c00c916b0431082db992dd5e194 to your computer and use it in GitHub Desktop.
logic-drills
/* ======= Traffic Lights =======
* You need to modify and update the
* JSBin below, so that when users
* click on the button, a randomly
* chosen traffic light turns on.
*/
function doTrafficLights() {
var activeLight = getActiveLight();
if (activeLight === 'red' ) {
return turnRed();
}
else if (activeLight === 'yellow' ) {
return turnYellow();
}
else return turnGreen();
}
function turnOffLights() {
$('.traffic-light').removeClass('yellow-on red-on green-on');
}
// Get CSS classes
function turnRed() {
turnOffLights();
$('.red-light').addClass('red-on');
}
function turnYellow() {
turnOffLights();
$('.yellow-light').addClass('yellow-on');
}
function turnGreen() {
turnOffLights();
$('.green-light').addClass('green-on');
}
// Return random colors
function getActiveLight() {
return (['red', 'green', 'yellow'])[Math.floor(Math.random() * 3)];
}
function handleClicks() {
$('.js-control-lights').click(function() {
doTrafficLights();
});
}
$(function() {
handleClicks();
});
/* ======= Error Alert =======
* In this drill, we've intentionally wired up
* the JavaScript code so that an error is triggered
* when you click on the "Click me" button.
* If you open the JavaScript console and run the JSBin below,
* you'll see that when doAllTheThings runs, it throws an error.
*/
function main() {
try {
doAllTheThings();
}
catch(e) {
console.error(e);
reportError(e);
}
}
function doAllTheThings() {
throw {
message: "Everything's ruined",
name: "FatalException",
toString: function(){return this.name + ": " + this.message;}
}
}
function reportError(e) {
$('.js-error-report').text("Uh oh, something went wrong! Here's what we know: " + e.message);
}
$(main);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment