Skip to content

Instantly share code, notes, and snippets.

@sebmarkbage
Last active May 10, 2016 16:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebmarkbage/060528aa2e57a629fe6bb0728d24a4bc to your computer and use it in GitHub Desktop.
Save sebmarkbage/060528aa2e57a629fe6bb0728d24a4bc to your computer and use it in GitHub Desktop.
Callbacks vs. Generators
function measure(box) {
const width = box.width + box.borderLeft + borderRight;
return {
width,
offset(position) {
return { left: position.left + box.borderLeft };
}
}
}
const measuredBox = measure(myBoxProps);
const width = measuredBox.width;
const initialOffset = measuredBox.offset({ left: 0 });
const shiftedOffset = measuredBox.offset({ left: 10 });
function measure(box) {
const width = box.width + box.borderLeft + borderRight;
const position = yield width;
return { left: position.left + box.borderLeft };
}
const measuredBox = measure(myBoxProps);
const width = measuredBox.next().value;
const initialOffset = measuredBox.next({ left: 0 });
// oops, now I need a different position
const replayedMeasuredBox = measure(myBoxProps);
replayedMeasuredBox.next(); // wasted
const shiftedOffset = replayedMeasuredBox.next({ left: 10 });
@risseraka
Copy link

risseraka commented May 3, 2016

Thanks again, I toyed with the code a bit, personally not a pro on generators.

Couple issues:

  • Missing star for generator function:
    function* measure(box) { /* ... */ }
  • borderRight is undefined should be box.borderRight.

But it's just a gist, who cares? ; )
Cheers.

@robcolburn
Copy link

I'm not sure what I the Generator version gives you… No Async, no repeating use, why bother? Might as well be a class

function measure(box) {
  if (!this instanceof measure) return new measure(box)
  // store original case we need it
  this.box = box
  this.width = box.width + 
}
measure.prototype.offset = function offset(){
  return {}

As a bonus, you have shareable/steal-able/unit-testable methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment