Last active
May 10, 2016 16:24
-
-
Save sebmarkbage/060528aa2e57a629fe6bb0728d24a4bc to your computer and use it in GitHub Desktop.
Callbacks vs. Generators
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
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 }); |
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
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 }); |
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
Thanks again, I toyed with the code a bit, personally not a pro on generators.
Couple issues:
function* measure(box) { /* ... */ }
box.borderRight
.But it's just a gist, who cares? ; )
Cheers.