Last active
July 5, 2019 08:47
-
-
Save ppeeou/f8519b1303c80e59a768daaafa212ed8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const curry = f => (a, ..._) => _.length > 0 | |
? f(a, ..._) | |
: (..._) => f(a, ..._); | |
const isIter = iter => iter && iter[Symbol.iterator]; | |
const toIter = iter => isIter(iter) ? iter[Symbol.iterator]() : function* () { } | |
const go1 = (a, f) => a instanceof Promise ? a.then(f) : f(a); | |
// const go2 = (acc, value, f) => value instanceof Promise | |
// ? value.then(value => f(acc, value)) | |
// : f(acc, value); | |
const go2 = (acc, value, f) => value instanceof Promise | |
? go1(value, v => f(acc, v)) | |
: f(acc, value); | |
// const go2 = (acc, value, f) => go1(value, v => f(acc, v)); | |
const add = (a, b) => a + b; | |
const reduce = curry((f, coll, acc) => { | |
const iter = toIter(coll); | |
if (!acc) acc = iter.next().value; | |
return go1(acc, function recur(acc) { | |
let cur; | |
while (!(cur = iter.next()).done) { | |
const value = cur.value; | |
acc = go2(acc, value, f); // 1*avail 15 | |
// acc = go1(value, v => f(acc, v)); // 2*not avail [object Promise]345 | |
// acc = value instanceof Promise ? // 3*not avail [object Promise]345 | |
// value.then(value => f(acc, value)) : | |
// f(acc, value); | |
// acc = (function (a, v, f) { | |
// return v instanceof Promise ? // 4*not avail [object Promise]345 | |
// v.then(v => f(a, v)) : | |
// f(a, v); | |
// }(acc, value, f)); | |
// acc = (function (a, v, f) { | |
// let b = a; | |
// return v instanceof Promise ? // 5*avail 15 | |
// v.then(v => f(b, v)) : | |
// f(a, v); | |
// }(acc, value, f)); | |
if (acc instanceof Promise) return acc.then(recur); | |
} | |
return acc; | |
}); | |
}); | |
(async function () { | |
const a = await reduce(add, [1, 2, Promise.resolve(3), 4, 5]); | |
console.log(a); | |
}()) | |
// 2,3,4 | |
// 생각 | |
// value가 Promise일 경우 Promise (Pending)값으로 acc 대입문 ("acc =" 이부분)으로 들어가고 acc값이 변경(참조값) | |
// value.then 이 비동기로 실행될때 acc가 Promise값이므로 f(acc,v)가 Promise값으로 평가 | |
// 1,5 이 가능이유 | |
// acc가 변경되기전에 값 복사가 이뤄지고 비동기 시점에는 복사된 값으로 평가하니 의도된 값으로 평가 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment