Functional Programming

After introducing the principles of functional programming - I think boils down to passing everything a function needs into the function explicitly, not relying on any global variables, not changing any external variables inside the function, as well as the objective that the function should always return the same value given the same input, there is a test using Array.map() and then a test to implement a map like function:

// the global Array
var arr = [23, 65, 98, 5];
Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
  for (let i = 0; i < this.length; i++) {
    newArray.push(this[i]*2);
  }
  // Add your code above this line
  return newArray;
};
var newArr = arr.myMap(function(item){
  return item * 2;
});
console.log(newArr); //[ 46, 130, 196, 10 ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

This passed but I think its wrong - should be using the callback function surely...

  for (let i = 0; i < this.length; i++) {
    newArray.push(callback(this[i]));
  }
1
2
3

Using map in conjunction with filter to first select movies from a list with a high rating (easy ES6 code for the filter part), then use the MDN example as a template for returning only bits of the object in the array - the title and the rating and ignoring the rest of each object:

var filteredList = watchList.filter(movie => movie.imdbRating >= 8.0).map(
  movie =>{ 
   var rObj = {}; //start with a fresh blank object for each element in the array
   rObj.title = movie.Title; //pick out only the two properties we want
   rObj.rating = movie.imdbRating;
   return rObj; //return an object for each iteration.
});
1
2
3
4
5
6
7

A non mutating sort:

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  let newArr = [];
  return newArr.concat(arr).sort((a,b) => a - b);
}
console.log(nonMutatingSort(globalArray));
1
2
3
4
5
6

Putting several functions together to create url slugs:

var globalTitle = "Winter Is Coming";
function urlSlug(title) {
  return title.toLowerCase().split(/[^a-z]/i).filter(word => word.length > 0).join("-");
}
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
console.log(urlSlug(" Winter Is  Coming")); // ditto
1
2
3
4
5
6