- Refactor Global Variables Out of Function1) Don't alter a variable or object - create new variables and objects and return them if need be from a function.
- 2) Declare function arguments - any computation inside a function depends only on the arguments, and not on any global object or variable.
- So far, we have seen two distinct principles for functional programming:
- Use the map Method to Extract Data from an Array
저렇게 그냥 object 형식을 가져다 쓸 수 있다는 건 처음 알았다. brace로 감지 않으면 에러가 난다.var rating = watchList.map(el => ({"title": el.Title, "rating": el.imdbRating}));
- Remember that the
map
method is a way to iterate over each item in an array. It creates a new array (without changing the original one) after applying a callback function to every element.
- Implement map on a Prototype
- 문제: map 기능을 prototype으로 구현하기
// the global Array var s = [23, 65, 98, 5]; Array.prototype.myMap = function(callback){ var newArray = []; // Add your code below this line // Add your code above this line return newArray; }; var new_s = s.myMap(function(item){ return item * 2; });
- 답
// the global Array var s = [23, 65, 98, 5]; Array.prototype.myMap = function(callback){ var newArray = []; this.forEach(item => newArray.push(callback(item))); // this return newArray; }; var new_s = s.myMap(function(item){ return item * 2; });
- Use the filter Method to Extract Data from an Array
Filter
doesn't alter the original array, just likemap
. It takes a callback function that applies the logic inside the callback on each element of the array. If an element returns true based on the criteria in the callback function, then it is included in the new array.
- Return part of an Array Using the Slice MethodIf the arguments are not provided, the default is to start at the beginning of the array through the end, which is an easy way to make a copy of the entire array.
- The
slice
method does not mutate the original array, but returns a new one.
- Remove Elements from an Array Using slice instead of splice
- The
splice
method mutates the original array it is called on.
- Using the concat Method
- JavaScript offers the
concat
method for both strings and arrays that work in the same way. It returns a new array and does not mutate either of the original arrays.
- Add Elements to the end of an Array Using concat instead of push
Push
adds an item to the end of the same array it is called on, which mutates that array.
Reference: freeCodeCamp Functional Programming