Skip to content

Instantly share code, notes, and snippets.

@humphd
Created September 15, 2020 18:53
Show Gist options
  • Save humphd/0531a8acdc04ad1467808c963549562a to your computer and use it in GitHub Desktop.
Save humphd/0531a8acdc04ad1467808c963549562a to your computer and use it in GitHub Desktop.
Examples from Week 2 Function Practice Exercises
// Function to create a JavaScript library name generator:
// generateName("dog") should return "dog.js"
function generateName(name) {
return name.endsWith('.') ? name + "js" : name + ".js";
}
let name = "cool"
let library = generateName(name);
console.log(name, library, generateName('cool.'));
// Check if a number is between two other numbers,
// being inclusive if the final argument is true:
// checkBetween(66, 1, 50, true) should return false.
function checkBetween(num, low, high, inclusive) {
if(inclusive) {
return num >= low && num <= high;
}
return num > low && num < high;
}
console.log(checkBetween(50, 1, 50), checkBetween(50, 1, 50, true));
// 4. Function to log all arguments larger than 255: showOutsideByteRange(1, 5, 233, 255, 256, 0)
// should log 256 to the console
function showOutsideByteRange() {
for(let i = 0; i < arguments.length; i++) {
let byte = arguments[i]
if(byte > 255) {
console.log(byte);
}
}
}
showOutsideByteRange(255, 1, 233, 255, 256, 300);
let showOutsideRange = function(low, high, ...values) {
for(let i = 0; i < values.length; i++) {
let value = values[i];
if(value < low || value > high) {
console.log(value);
}
}
};
showOutsideRange(0, 255, 1, -5, 233, 255, 256, 300);
// Function to calculate the HST (13%) on a purchase amount
function calculateHST(amount) {
return amount * percent;
}
function calculateHST(amount) {
if(!percent) {
percent = 0.13;
}
return amount * percent;
}
function calculateHST(amount, percent) {
percent = percent || 0.13
return amount * percent;
}
function calculateHST(amount, percent=0.13) {
return amount * percent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment