Functions - Exercise

by Shane Porter

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
 */

// 1. closure here
function createStore() {

    // "private"
	var data = {};
    
	return function(key, val) {        			
        
        return val === undefined 
			? data[key]			// we are getting
			: data[key] = val;  // we are setting
        
    };
    
}

var store = createStore();
store('count',0);
var c = store('count');

function warn() {
    if (store('count') < 1) {
        c=1;
    console.log('You have been warned ' + c + ' time');
        		store('count', c);
                }
                else if (store('count') >3) 
                {
                //nothing
                }
                else
                {
                c++;
                console.log('You have been warned ' + c + ' times');
                            store('count', c);
    }
}
    



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;

}

//C = ( F - 32) / 1.8
//F =  C Ă— 1.8 + 32

var fh = convert.bind(null, 1.8, 32);
fh(32);

// 3. IIFE here
/*
for (var i = 1; i <= 5; i++) {
	setTimeout(function() {
		console.log(i);
	}, i * 1000);
} */