Difference between revisions of "Functions"
(16 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
==Functions== | ==Functions== | ||
== [[Coding Challenge1| Coding Challenge Console Quiz]] == | |||
<pre> | <pre> | ||
function generator(input){ | function generator(input){ | ||
Line 12: | Line 14: | ||
var calc = generator(900); | var calc = generator(900); | ||
console.log(calc()); | console.log(calc()); | ||
== Passing Functions as Arguments == | == Passing Functions as Arguments == | ||
<pre> | <pre> | ||
Line 86: | Line 89: | ||
== Closures == | == Closures == | ||
Same Program as above but written using closures | Same Program as above but written using closures. <br> | ||
'''Closures is basically making variables private.''' | |||
<pre> | <pre> | ||
function interQ(job) { | function interQ(job) { | ||
Line 105: | Line 109: | ||
interQ('teacher')('Robert'); | interQ('teacher')('Robert'); | ||
</pre> | </pre> | ||
==Bind Call and Apply Methods == | ==Bind Call and Apply Methods == | ||
=== Call Function Also know as Method Borrowing === | === Call Function Also know as Method Borrowing === | ||
Allow you to call a function and set the this variable manually | Allow you to call a function and set the this variable manually <br /> | ||
A John object is created with a presentation function, along with other attributes. We are now going to create another object Emily with a few attributes, but without the presentation function, However we would like to use that function with the Emily Object. | A John object is created with a presentation function, along with other attributes. <br />We are now going to create another object Emily with a few attributes, but without the presentation function, However we would like to use that function with the Emily Object. | ||
<pre> | <pre style="color: green"> | ||
var john = { | var john = { | ||
name: 'John', | name: 'John', | ||
Line 144: | Line 149: | ||
</pre> | </pre> | ||
Call the Emily object Utilizing the presentation function form john. This call()function allows the 'this' keyword to be applicable to Emily and not the john object | Call the Emily object Utilizing the presentation function form john. This call() function allows the 'this' keyword to be applicable to Emily and not the john object <br /> | ||
The First argument of the call() function is the 'this' which in this case is emily. | '''The First argument of the call() function is the 'this' which in this case is emily.''' | ||
john.presentation.call(emily, 'friendly', 'afternoon'); | john.presentation.call(emily, 'friendly', 'afternoon'); | ||
Line 158: | Line 163: | ||
var emilyFormal = john.presentation.bind(emily, 'formal'); | var emilyFormal = john.presentation.bind(emily, 'formal'); | ||
emilyFormal('formal'); | emilyFormal('formal'); | ||
Another Example of the bind method Applied to the Earlier Example | |||
<pre style="color:green"> | |||
var years = [2001, 1950, 1958, 1967]; | |||
function arrayCalc(arr, fn) { | |||
//empty function to hold return | |||
var arrRes = []; | |||
for (var i = 0; i < arr.length; i++) { | |||
arrRes.push(fn(arr[i])); | |||
} | |||
return arrRes; | |||
} | |||
function calculateAge2(el) { | |||
return 2016 - el; | |||
} | |||
function isFullAge(limit, el) { | |||
return el >= limit; | |||
} | |||
var ages = arrayCalc(years, calculateAge); | |||
var fullJapan = arrayCalc(ages, isFullAge.bind(this, 20)); | |||
</pre> | |||
By binding the isFullAge, we are able to pass the preset of 20 into the arrayCal function. | |||
=== Apply Method === | |||
'''Same as the bind Method but the arguments are passed as an array.''' <br /> | |||
<code>john.presentation.apply(emily, ['friendly', 'afternoon'])'</code> | |||
==Timers and Intervals== | ==Timers and Intervals== |
Latest revision as of 13:29, 9 November 2016
Functions
Coding Challenge Console Quiz
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.
Closures is basically making variables private.
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
Call Function Also know as Method Borrowing
Allow you to call a function and set the this variable manually
A John object is created with a presentation function, along with other attributes.
We are now going to create another object Emily with a few attributes, but without the presentation function, However we would like to use that function with the Emily Object.
var john = { name: 'John', age: '26', job: 'teacher', presentation: function(style, timeOfDay) { if (style === 'formal') { console.log( 'Good ' + timeOfDay + ', Ladies and Gents I\'m ' + this.name + ' Job is ' + this.job + ' and years old ' + this.age ); } else if (style == 'friendly') { console.log( 'Whats Up ' + timeOfDay + ', Dudes I\'m ' + this.name + ' Job is ' + this.job + ' and years old ' + this.age ); } // end else if } // presentation } // end john
Call the John Object
john.presentation('formal', 'morning'); john.presentation('friendly', 'evening');
Create a new Emily object
var emily = { name: 'emily', age: '29', job: 'designer', } // end emily
Call the Emily object Utilizing the presentation function form john. This call() function allows the 'this' keyword to be applicable to Emily and not the john object
The First argument of the call() function is the 'this' which in this case is emily.
john.presentation.call(emily, 'friendly', 'afternoon');
Bind Method
Same as the call() but it doesn't call the function right away but creates a copy of it. It allows you to preset some parameters passed to the internal function
var johnFriendly = john.presentation.bind(john, 'friendly'); johnFriendly('morning'); johnFriendly('night');
The Presentation function was preset with 'friendly' argument An example using emily. The emily is the "this"
var emilyFormal = john.presentation.bind(emily, 'formal'); emilyFormal('formal');
Another Example of the bind method Applied to the Earlier Example
var years = [2001, 1950, 1958, 1967]; function arrayCalc(arr, fn) { //empty function to hold return var arrRes = []; for (var i = 0; i < arr.length; i++) { arrRes.push(fn(arr[i])); } return arrRes; } function calculateAge2(el) { return 2016 - el; } function isFullAge(limit, el) { return el >= limit; } var ages = arrayCalc(years, calculateAge); var fullJapan = arrayCalc(ages, isFullAge.bind(this, 20));
By binding the isFullAge, we are able to pass the preset of 20 into the arrayCal function.
Apply Method
Same as the bind Method but the arguments are passed as an array.
john.presentation.apply(emily, ['friendly', 'afternoon'])'
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));