Created
November 18, 2016 11:22
-
-
Save frank-dspeed/8186306c74324cfd4ce6eb6fe04b0773 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
btw, everyone ... for this API | |
var saltShaker = new SaltShaker(); | |
saltShaker.fill(); | |
saltShaker.shake() //-> "salt" | |
saltShaker.shake() //-> "salt" | |
saltShaker.shake() //-> null | |
saltShaker.empty //-> true | |
It can be implemented like this imperatively: | |
SaltShaker = can.DefineMap.extend({ | |
saltCount: {type: "number", value: 0}, | |
fill: function(){ | |
this.saltCount = 2; | |
}, | |
shake: function(){ | |
var hasSalt = this.saltCount | |
this.saltCount = hasSalt ? this.saltCount - 1 : 0; | |
return hasSalt ? "salt" : null | |
}, | |
get empty() { | |
return ! this.saltCount | |
} | |
}); | |
or like this declaratively with the can-define-stream | |
var SaltShaker = can.DefineMap.extend({ | |
saltCount: { | |
stream: function() { | |
console.log("YES") | |
return this.stream("fill") | |
.merge(this.stream("shake")) | |
.scan(function(prev, ev){ | |
if(ev.type === "fill") { | |
return 2; | |
} else { | |
return prev > 0 ? prev - 1 : 0; | |
} | |
},0); | |
} | |
}, | |
fill: function() { | |
this.dispatch("fill"); | |
}, | |
shake: function() { | |
var hadSalt = this.saltCount; | |
this.dispatch("shake"); | |
return hadSalt ? "salt" : null; | |
}, | |
get empty() { | |
return !this.saltCount; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment