JavaScriptmancy - Basics - Function Defaults - Exercises
Function Defaults - Exercises
by vintharas
HTML
<pre><code id="theWorld">
</code></pre>
CSS
pre {
font-size: 0.9rem;
padding: 2%;
background: #333;
color: white;
}
pre .world {
display: block;
white-space: pre-wrap;
}
pre .world-error{
color: rgba(255,0,0,0.7);
}
pre .world-info {
color: grey;
font-style: italic;
padding: 10px 0;
}
pre .world-spell{
color: rgba(90,90,255,1);
}
Babel + JSX
'use strict'
// log stuff in the home-made console to the write in addition to
// logging it to the browser console
startWorld();
/*
JavaScript-mancy: Mastering the Arcane Art of Writing Awesome JavaScript
Chapter 03 - Useful Function Patterns: Default Argument - Exercises
*/
randalf.says('See? By using defaults you can make ' +
'your spellcasting more effective');
mooleen.says('hmm... indeed... indeed...');
mooleen.says('Do I get to know why I am here? And what here is?');
randalf.says('Sure! Just start practicing while I go get us lunch');
// exercises
narrate("=== ### Time to light a Fire! === ");
narrate("Improve this fire function using defaults with ES5.");
function fire(mana, target){
if (mana > 10) console.log('An enormous fire springs to life on ' + target);
else if (mana > 4) console.log('You light a strong fire on ' + target);
else if (mana > 2) console.log('You light a small fire on ' + target);
else if (mana > 0) console.log('You try to light a fire but ' +
'only achieve in creating teeny tiny sparks. Beautiful but useless.');
}
mooleen.says('damn old man...');
mooleen.says('let me modify this spell for the most cost-effective use case');
function fireImproved(mana, target){
mana = mana || 3;
target = target || 'dry wood';
if (mana > 10) console.log('An enormous fire springs to life on ' + target);
else if (mana > 4) console.log('You light a strong fire on ' + target);
else if (mana > 2) console.log('You light a small fire on ' + target);
else if (mana > 0) console.log('You try to light a fire but ' +
'only achieve in creating teeny tiny sparks. Beautiful but useless.');
}
mooleen.weaves('fireImproved()');
// => You light a small fire on dry wood;
mooleen.says('aha!');
narrate("=== ### And now try ES6 Defaults === ");
narrate("Improve the fire function using ES6 defaults.");
function fireImprovedES6(mana=3, target='dry wood'){
if (mana > 10) console.log('An enormous fire...