function* bankAccount() {
let balance = 0;
while (balance >= 0) {
balance += yield balance;
}
return 'bankrupt! ';
}
let userAccount = bankAccount();
console.log(userAccount.next());
console.log(userAccount.next(10));
console.log(userAccount.next(-15));
...this code works - I've run it and after the third call of next(), it returns bankrupt - but why? Surely when next() is called the third time, the loop will check the balance (which will still be 10 at that point), and then add -15 to the balance, and yield out -5...leaving the next iteration to yield bankrupt.
But thats obviously not the case, the balance seems to be updated with the yield value before the loop checks the current balance, but if that line of code is running first, then why is the loop running at all? wouldn't it just be yielding out the updated balance instantly?...so, which code is being run when?
Order of operations:
let balance = 0;
while (balance >= 0) {
- balance is 0 hereyield balance
- yields 0balance += <value passed to next = 10>
- balance is 10 after thatwhile (balance >= 0) {
- balance is 10yield balance
- yields 10balance += <value passed to next = -5>
- balance is -5 after thatwhile (balance >= 0) {
- balance is -5 so breakreturn 'bankrupt! ';
function* bankAccount() {
let balance = 0;
while (balance >= 0) {
balance += yield balance;
console.log('inside loop', balance)
}
console.log('after loop', balance)
return 'bankrupt! ';
}
let userAccount = bankAccount();
userAccount.next();
userAccount.next(10);
userAccount.next(-15);