Functions - Exercise
by manu troiani
JavaScript
/*
* Functions - Exercise
*
* 1. Create a closure that returns a function that accepts msg and limit. The returned
* function will alert the msg, but only up to the limit times
* 2. Using the provided convert() function below, use .bind() to create new functions that
* can convert various units, like celcius to fahrenheit, miles to kilometers, etc
* 3. Use an IIFE make the provided function output the numbers in the order expected
*/
function createWarn( msg, limit ) {
console.log(msg);
console.log(limit);
var c = 0;
console.log( c );
return function(){
if (c < limit ){
console.log(msg)
alert('You have been warned'+ c+ 'times');
c++;
}
else{
alert('nop!');
console.log('nop');
}
}
}
//var warn = createWarn ('warn', 4);
/*
// 1. closure here
warn(); // 'You have been warned 1 time'
warn(); // 'You have been warned 2 times'
warn(); // 'You have been warned 3 times'
warn(); // noop
*/
// 2. bind here
function convert(factor, offset, input) {
return (input + (offset || 0)) * factor;
}
// 1mile = 1.60934
// 2miles = 1.60934 * 2
// 100000 miles = 160934
//console.log ( convert( 2, 1, 3) );
convert2Miles= convert.bind(null, 1.60934 , 0);
console.log (convert2Miles(2));
// 1 Celsius = 33.8 F
//// T( F ) = T ( c ) * 1.8 + 32
//
var fact = 5/9;
convert2Celsius = convert.bind(null, fact , -32);
console.log('***** 71.6 F should be about 22 C degrees ***** ');
console.log('***** the convertion of 71.6F is: ***** ');
console.log(convert2Celsius(71.6)+'C');
convert2fahrenheit = function() {
var out = convert.bind(null, fact, 0 ) + 32) ;
return out;
};
console.log('***** the convertion of 22C is: ***** ');
console.log(convert2fahrenheit(22) + 'F');
/*
3. Use an IIFE make the provided function output the numbers in the order expected
// 3. IIFE here
for (var i = 1; i <= 5; i++) {
setTimeout(function()...