Functions

From rbachwiki
Revision as of 22:25, 7 November 2016 by Bacchas (talk | contribs)
Jump to navigation Jump to search

Functions

function generator(input){
 var number= input;
 return function(){
 return number * 2;
};
}

Call function

var calc = generator(900);
console.log(calc());

Passing Functions as Arguments


var years = [1950, 1950, 1958, 1967];

function arrayCalc(arr, fn) {
    //empty function to hold return
    var arrRes = [];
    for (var i = 0; i < arr.length; i++) {
        // this takes the calculateAge2 function(i) and for each i 
        // it calculates the age and push it to the array which is returned.
        arrRes.push(fn(arr[i]));
    }
    return arrRes;
}

function calculateAge2(el) {
    return 2016 - el;
}
// the calculateAge2 does not have the () because we don't want to call it there
// its called a callback function because it is called when it's passed to the other function

var ages = arrayCalc(years, calculateAge2);
function isFullAge(el) {
    return el >= 18;
}
console.log(ages);

Another Call Back function using the function above, this calculates the optimal heart rate based on a persons age

function maxHeartRate(el) {
    if (el >= 18 && el <= 81) {
        return Math.round(206.9 - (0.67 * el));

    } else {
        return -1;
    }

} // maxHeartRate
var rates = arrayCalc(ages, maxHeartRate);
console.log(rates);

Functions Returning Functions

function interviewQuestion(job) {
    if (job === 'designer') {
        return function(name) {
            console.log(name + " Explain UX");
        }
    } else if (job === 'teacher') {
        return function(name) {
            console.log(name + ', What subject do you teach');
        }

    } else {
        return function(name) {
            console.log(name + ' what do you do');
        }
    }
} // interviewQuestion

var teacherQuestion = interviewQuestion('teacher');
teacherQuestion('john');

var designerQuestion = interviewQuestion('designer');
designerQuestion('john');

Another way to call the function without a variable

interviewQuestion('teacher')('mark');

line is evaluated from left to right, teacher is called first returning a function then mark is passed into that function.

Closures

Same Program as above but written using closures

function interQ(job) {

    return function(name) {
        if (job === 'designer') {
            console.log(name + " Explain UX");

        } else if (job === 'teacher') {
            console.log(name + ', What subject do you teach');
        } else {

            console.log(name + ' what do you do');
        }
    }
}

interQ('teacher')('Robert');

Bind Call and Apply Methods

Timers and Intervals

setTimeout(function(){
console.log('finished');
},2000);

Intervals - will run ever 5 seconds

setInterval(function(){
console.log('ping');
},500);

Interval will stop

var interval = setInterval(function(){
console.log('ping');
});
setTimeout(function(){
clearInterval(interval);
},2500);

Immediately Invoked Functions

(function() {
var score = Math.random() * 10;
console.log(score >=5);
})();

Passing an argument into the function

(function(goodluck) {
var score = Math.random() * 10;
console.log(score >=5 - goodluck);
})(5);

Adding the 5 in the closing parenthesis will pass it as an argument

Transforming Format and Values

parseInt();
toFixed(3) rounds to 3 decimal places

String Functions

a = "abc";
a.length;
a[2]; = c
a.charAt(2); = c
a.concat('add to string');
a.toUpperCase();
a.split(' '); will split string using supplied delimiter into a array;
a.trim() // trim white space before and after a string.

Sorting Numbers

Will work on numbers only

var numbers=[11,2,3,33];

var sortAscending = function(x,y){
  return x -y;
}
console.log(numbers.sort(sortAscending));

Will work on numbers and text


var numbers=[11,2,3,33];

var sortAscending = function(x,y){
  if(x > y) return 1;
  if(y>x) return -1;
 return 0;
}
console.log(numbers.sort(sortAscending));

Sort Descending

Will work on numbers and text


var numbers=[11,2,3,33];

var sortAscending = function(x,y){
  if(x > y) return -1;
  if(y>x) return 1;
  return 0;
}
console.log(numbers.sort(sortAscending));

Back To Top- Home - Category