Skip to content

Instantly share code, notes, and snippets.

@gaogao-9
Last active March 16, 2016 10:24
Show Gist options
  • Save gaogao-9/6860884534ee5088eddd to your computer and use it in GitHub Desktop.
Save gaogao-9/6860884534ee5088eddd to your computer and use it in GitHub Desktop.
世界一有名なステートマシンの話としての自動販売機
const vm = vendingMachine();
console.log(vm.next()); // {"value":[0,0],"done":false}
console.log(vm.next(50)); // {"value":[50,0],"done":false}
console.log(vm.next(50)); // {"value":[100,0],"done":false}
console.log(vm.next(100)); // {"value":[80,1],"done":false}
console.log(vm.next(10)); // {"value":[90,0],"done":false}
console.log(vm.next(10)); // {"value":[100,0],"done":false}
console.log(vm.next(10)); // {"value":[110,0],"done":false}
console.log(vm.next(10)); // {"value":[0,1],"done":false}
console.log(vm.next(10)); // {"value":[10,0],"done":false}
console.log(vm.next(10)); // {"value":[20,0],"done":false}
console.log(vm.next(500)); // {"value":[40,4],"done":false}
// 初期状態は自販機内部金額は0円。
// ユーザーは0円(何も入れない)、10円、50円、100円、500円のうちどれか1つを投入できる。
// 金額を入れる度に、内部金額加算される。
// 内部金額120円を超えると、ジュースを買えるだけ購入する。
// 金額を入れる度に、内部で保持する金額と、ジュースの本数を出力する
function* vendingMachine(){
let yen = 0;
let drink = 0;
while(true){
const coin = yield [yen, drink];
if((coin === 0) || (coin === window.undefined)) continue;
if((coin !== 10) && (coin !== 50) && (coin !== 100) && (coin !== 500)){
throw new TypeError("まともな金を入れろ");
}
yen += coin;
drink = ~~(yen / 120);
yen -= drink*120;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment