Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amandarfernandes/fe5966f6641d1da698de2de5d9df7500 to your computer and use it in GitHub Desktop.
Save amandarfernandes/fe5966f6641d1da698de2de5d9df7500 to your computer and use it in GitHub Desktop.
JS ArrowFunction Exercises
/* 1 - Refactor the following code to use ES2015 arrow functions - make sure your function is also called tripleAndFilter
function tripleAndFilter(arr){
return arr.map(function(value){
return value * 3;
}).filter(function(value){
return value % 5 === 0;
})
}
*/
var tripleAndFilter = arr => arr.map(val => val*3).filter(value => value % 5 === 0);
/* 2 - Refactor the following code to use ES2015 arrow functions. Make sure your function is also called doubleOddNumbers
function doubleOddNumbers(arr){
return arr.filter(function(val){
return val % 2 !== 0;
}).map(function(val){
return val *2;
})
}
*/
var doubleOddNumbers = arr=>arr.filter(num=>num % 2 !== 0).map(val=>val *2);
/* 3 - Refactor the following code to use ES2015 arrow functions. Make sure your function is also called mapFilterAndReduce.
function mapFilterAndReduce(arr){
return arr.map(function(val){
return val.firstName
}).filter(function(val){
return val.length < 5;
}).reduce(function(acc,next){
acc[next] = next.length
return acc;
}, {})
}
*/
var mapFilterAndReduce = arr => arr.map(item=>item.firstName).filter(name=>name.length < 5).reduce((acc,next)=>{acc[next] = next.length; return acc}, {});
/* 4 - Write a function called createStudentObj which accepts two parameters, firstName and lastName and returns an object with the keys of firstName and lastName with the values as the parameters passed to the function.
Example:
createStudentObj('Elie', 'Schoppik') // {firstName: 'Elie', lastName: 'Schoppik'}
*/
var createStudentObj = (firstName,lastName) => ({firstName:firstName,lastName:lastName});
/* 5 - Given the following code:
Refactor this code to use arrow functions to make sure that in 1000 milliseconds you console.log 'Hello Colt'
var instructor = {
firstName: "Colt",
sayHi: function(){
setTimeout(function(){
console.log('Hello ' + this.firstName)
},1000)
}
}
*/
var instructor = {
firstName: "Colt",
sayHi: function(){
setTimeout(()=>{console.log('Hello ' + this.firstName)},1000)
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment