Skip to content

Instantly share code, notes, and snippets.

@gilesbradshaw
Created September 23, 2018 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilesbradshaw/d232980b31ead8417108739765d68993 to your computer and use it in GitHub Desktop.
Save gilesbradshaw/d232980b31ead8417108739765d68993 to your computer and use it in GitHub Desktop.
// a reduce function for a generator
// the result of the reducer function gets passed into next
function reduce(
reducer,
seed,
) {
const gen = this(seed);
let acc = seed;
let results = [];
let next = gen.next();
while (!next.done) {
results = [
...results,
next.value,
];
acc = reducer(
acc,
next.value,
);
next = gen.next(
acc,
);
}
return {
acc,
results,
};
}
function* generate(param) {
let _param = param;
_param = yield _param + 1;
_param = yield _param + 1;
_param = yield _param + 1;
_param = yield _param + 1;
_param = yield _param + 1;
return _param;
}
generate::reduce(
(acc, val) =>
acc + val,
1,
)
// { acc: 63, results: [2, 4, 8, 16, 32] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment