6. 함수형프로그래밍

함수형 프로그래밍

함수의 장점을 살려 프로그래밍 하는 방식으로 그 특징은 다음과 같다.

  1. 함수전달

  2. 필터와 파이프

  3. 어큐뮬레이터

1. 함수전달

함수가 first class 이여서, 변수에 할당, 전달이 가능해진다. 즉 함수를 객체로 받아들이고 변수에 저장하여 활용이 될 수 있다는 것이다.

구현코드

  var HamiltonianTour = (function () {
    function HamiltonianTour(options) {
      this.options = options;
    }

    HamiltonianTour.prototype.startTour = function () {
      if (this.options.onTourStart && typeof (this.options.onTourStart) === 'function') {
        this.options.onTourStart();
        this.visitAttraction("King's Landing");
        this.visitAttraction("Winterfell");
        this.visitAttraction("Eyrie");

        if (this.options.onTourCompletion && typeof (this.options.onTourCompletion) === 'function') {
          this.options.onTourCompletion();
        }
      }
    };

    HamiltonianTour.prototype.visitAttraction = function (attractionName) {
      if (this.options.onEntryToAttraction && typeof (this.options.onEntryToAttraction) === 'function') {
        this.options.onEntryToAttraction(attractionName);
      }

      // 관광명소에서 하는 일
      if (this.options.onExitFromAttraction && typeof (this.options.onExitFromAttraction) === 'function') {
        this.options.onExitFromAttraction(attractionName);
      }
    };

    return HamiltonianTour;
  })();

  console.log("\n**** 1. 함수전달 ****\n");
  var tour = new HamiltonianTour({
    onEntryToAttraction: function (cityName) {
      console.log("I'm delighted to be in ~ " + cityName);
    },
    onTourStart: function () {

    }
  });
  tour.startTour();

2. 필터와 파이프

함수결과를 함수의 입력으로 적용할 수 있도록 구현. 유닉스의 | 기호에 해당하며, 자바스크립트에서는 이를 함수체인을 통해 비슷하게 구현하고 있음. 필터링을 통해 객체를 필터링 하여 전달이 가능하고, 파이프를 통해 연결하는데 자스에서는 체인이다.

구현코드

  // 2. 필터와 파이프
  Array.prototype.where = function (inclusionTest) {
    var results = [];
    for (let i = 0; i < this.length; i++) {
      if (inclusionTest(this[i])) {
        results.push(this[i]);
      }
    }
    return results;
  };

  console.log("\n**** 2. 필터와 파이프 ****\n");

  // where (필터링)
  var items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  console.log(
    items
    .where(function (thing) {
      return thing % 2 == 0;
    })
    .where(function (thing) {
      return thing % 3 == 0;
    })
  );

  // select (get)
  Array.prototype.select = function (projection) {
    var results = [];
    for (let i = 0; i < this.length; i++) {
      results.push(projection(this[i]));
    }
    return results;
  };

  var children = [
    {id: 1, name: "Rob"},
    {id: 2, name: "Hang"},
    {id: 3, name: "so"},
    {id: 4, name: "Lee"},
    {id: 5, name: "yoon"}
  ];

  var filteredChildren = children
  .where(function (x) {
    return x.id % 2 == 0;
  })
  .select(function (x) {
    return x.name;
  });
  console.log(filteredChildren);

3. 어큐뮬레이터

말그대로 계싼하는 과정. 리듀싱?과 동일 개념을 보임.

  1. 이터레이터가 가능한 객체 (배열, 객체, 유사배열 등)

  2. 재귀구조의 실행 함수

  3. 재귀구조 안에서 실행될 함수 정의

구현코드

  // 3. 어큐뮬레이터
  var passants = [
    {name: "Jory Cassel", taxesOwed: 11, bankBalance: 50},
    {name: "Vardis Egen", taxesOwed: 15, bankBalance: 20}
  ];

  function TaxCollector() {
  }

  TaxCollector.prototype.collect = function (items, value, projection) {
    if (items.length > 1) {
      return projection(items[0]) + this.collect(items.slice(1), value, projection);
    }
    return projection(items[0]);
  };

  // 실행
  console.log(
    TaxCollector.prototype.collect(passants, 20, function (item) {
        return Math.min(item.taxesOwed, item.bankBalance);
      }
    )
  );  // 11 + 15 = 26

Last updated