Skip to content

Commit

Permalink
2024-11-12
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuni-Q committed Nov 11, 2024
1 parent ea3d36b commit 783a324
Showing 1 changed file with 99 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
---
title: 08์žฅ ํ•จ์ˆ˜์ž
date: 2024-11-11 23:11:36
category: ํ•จ์ˆ˜ํ˜• ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์ž…๋ฌธ
tags: []
draft: true
---

- ํ•จ์ˆ˜์ž(functor)๋ผ๋Š” ๊ฐœ๋…์€ ์ˆœ์ˆ˜ํ•˜๊ฒŒ ํ•จ์ˆ˜ํ˜• ๋ฐฉ๋ฒ•์œผ๋กœ ์—๋Ÿฌ๋ฅผ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋„๋ก ๋„์™€์ค€๋‹ค.

## ํ•จ์ˆ˜์ž

- ํ•จ์ˆ˜์ž๋ž€ ๊ธฐ๋ณธ์ ์ธ ๊ฐ์ฒด(๋‹ค๋ฅธ ์–ธ์–ด์—์„œ๋Š” ํƒ€์ž… ํด๋ž˜์Šค)๋กœ, ๊ฐ์ฒด ๋‚ด์˜ ๊ฐ ๊ฐ’์„ ์‹คํ–‰ํ•  ๋•Œ ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ์‹คํ–‰ํ•˜๋Š” map ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค.

### ํ•จ์ˆ˜์ž๋Š” ์ปจํ…Œ์ด๋„ˆ๋‹ค

- ๊ฐ„๋‹จํ•˜๊ฒŒ ํ•จ์ˆ˜์ง€๋Š” ๊ฐ’์„ ๊ฐ–๊ณ  ์žˆ๋Š” ์ปจํ…Œ์ด๋„ˆ๋‹ค.
- ํ•จ์ˆ˜์ž๋Š” map ์ปจํŠธ๋ž™ํŠธ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๊ฐ์ฒด๋‹ค.

### map ๊ตฌํ˜„

- map ํ•จ์ˆ˜๋Š” Container์˜ ๊ฐ’์„ ๋ฐ›๊ณ  ํ•ด๋‹น ๊ฐ’์— ์ „๋‹ฌ๋œ ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•œ ํ›„ ๊ฒฐ๊ณผ๋ฅผ ๋‹ค์‹œ Container์— ๋„ฃ๋Š”๋‹ค.

## MayBe ํ•จ์ˆ˜์ž

- MayBe ํ•จ์ˆ˜์ž๋Š” ์ข€ ๋” ํ•จ์ˆ˜์ ์ธ ๋ฐฉ๋ฒ•์œผ๋กœ ์ฝ”๋“œ์˜ ์—๋Ÿฌ๋ฅผ ํ•ธ๋“ค๋งํ•  ์ˆ˜ ์žˆ๋‹ค.

```js
const MayBe = function (val) {
this.value = val;
};

MayBe.of = function (val) {
return new MayBe(val);
};

MayBe.prototype.isNothing = function () {
return this.value === null || this.value === undefined;
};

MayBe.prototype.map = function (fn) {
return this.isNothing() ? MayBe.of(null) : MayBe.of(fn(this.value));
};

// ์ผ๋ฐ˜์ ์ธ ๋ช…๋ นํ˜• ๋ฐฉ๋ฒ•
let value = 'string';
if (value != null || value != undefined) return value.toUpperCase();
```

- map์— ์ „๋‹ฌ๋œ ํ•จ์ˆ˜๊ฐ€ null/undefined๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋” ๋ผ๋„ MayBe๋Š” ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.
- ๋ชจ๋“  map ํ•จ์ˆ˜๊ฐ€ null/undefined๋ฅผ ๋ฐ›๋Š” ๊ฒƒ๊ณผ ์ƒ๊ด€์—†์ด ํ˜ธ์ถœ ๋œ๋‹ค๋Š” ์ ์ด๋‹ค.

### ์‹ค์ œ ์‚ฌ์šฉ์ž ์ผ€์ด์Šค

- ์—๋Ÿฌ๋ฅผ ๋˜์ง€์ง€ ์•Š๋Š”๋‹ค. map ํ•จ์ˆ˜๊ฐ€ ์‘๋‹ต์—์„œ data๋ฅผ ์–ป์œผ๋ ค ํ•ด๋„(์ด ๊ฒฝ์šฐ์—๋Š” ์กด์žฌํ•˜์ง€ ์•Š์Œ) MayBe.of(null)์„ ๋ฐ˜ํ™˜ํ•ด์„œ ํ•ด๋‹น map์ด ์ „๋‹ฌ๋œ ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค.
- ๋งค์šฐ ์„ ์–ธ์ ์œผ๋กœ ๋ณด์ธ๋‹ค.

## Either ํ•จ์ˆ˜์ž

- Either๋Š” ๋ถ„๊ธฐ(branching-out) ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•œ๋‹ค.

### Either ๊ตฌํ˜„

```js
const Nothing = function (val) {
this.value = val;
};

Nothing.of = function (val) {
return new Nothing(val);
};

Nothing.prototype.map = function (fn) {
return this;
};

const Some = function (val) {
this.value = val;
};

Some.of = function (val) {
return new Some(val);
};

Some.prototype.map = function (fn) {
return Some.of(fn(this.value));
};
```

- Some์—์„œ๋Š” ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•˜๋Š”๋ฐ, Nothing์—์„œ๋Š” ์‹คํ–‰ํ•˜์ง€ ์•Š๋Š”๋‹ค.

```js
const Either = {
Some: Some,
Nothing: Nothing,
};
```

- ์ž๋ฐ” ๊ฒฝํ—˜์ด ์žˆ๋‹ค๋จผ Either๋Š” ์ž๋ฐ” 8์˜ Optional๊ณผ ์œ ์‚ฌํ•จ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค. ์‚ฌ์‹ค Optional์€ ํ•จ์ˆ˜์ž๋‹ค.

0 comments on commit 783a324

Please sign in to comment.