티스토리 뷰

  • 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
    var rating = watchList.map(el => ({"title": el.Title, "rating": el.imdbRating})); 
    저렇게 그냥 object 형식을 가져다 쓸 수 있다는 건 처음 알았다. brace로 감지 않으면 에러가 난다.
  •  
  • Remember that the mapmethod 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
  • Filterdoesn't alter the original array, just like map. 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 slicemethod does not mutate the original array, but returns a new one.
 
  • Remove Elements from an Array Using slice instead of splice
  • The splicemethod mutates the original array it is called on.
 
  • Using the concat Method
  • JavaScript offers the concatmethod 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
  • Pushadds an item to the end of the same array it is called on, which mutates that array.

Reference: freeCodeCamp Functional Programming

 

'공부일지(TIL) > Others' 카테고리의 다른 글

HTML5로 카드 만들기 (with Canvas API)  (0) 2019.06.11
Design Patterns Intro  (0) 2019.05.17
Node File System Module  (0) 2019.04.28
Functional Programming 3  (0) 2019.03.18
Functional Programming 1  (0) 2019.03.12
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함