|
| 1 | +const actions = [ |
| 2 | + 'jumped', |
| 3 | + 'took a running leap', |
| 4 | + 'tried again and again', |
| 5 | + // 'miraculously flew', // try uncommenting this to change the result |
| 6 | +] |
| 7 | + |
| 8 | +const grapes = { |
| 9 | + qualities: ['beautiful', 'ripe', 'ready to burst with juice'], |
| 10 | + status: 'hanging from a vine', |
| 11 | + respond: function(foxAction) { |
| 12 | + if (foxAction === 'miraculously flew') { |
| 13 | + return 'eaten' |
| 14 | + } else { |
| 15 | + return null |
| 16 | + } |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +const fox = { |
| 21 | + attemptsMade: 0, |
| 22 | + feelings: ['hungry', 'a sense of longing'], |
| 23 | + hasTriedtoReachGrapes: false, |
| 24 | + hasReachedGrapes: false, |
| 25 | + |
| 26 | + tryToEatGrapes: function() { |
| 27 | + for (let action of actions) { |
| 28 | + result = grapes.respond(action); |
| 29 | + fox.attemptsMade += 1; |
| 30 | + if (result) { |
| 31 | + fox.hasReachedGrapes = true; |
| 32 | + fox.feelings = ['elation', 'pride']; |
| 33 | + grapes.qualities = ['delicious']; |
| 34 | + grapes.status = 'eaten'; |
| 35 | + break; |
| 36 | + } |
| 37 | + } |
| 38 | + if (!fox.hasReachedGrapes) { |
| 39 | + fox.feelings = ['disgust']; |
| 40 | + grapes.qualities = ['sour']; |
| 41 | + } |
| 42 | + fox.hasTriedtoReachGrapes = true; |
| 43 | + }, |
| 44 | + |
| 45 | + getTriedText: function() { |
| 46 | + if (fox.hasTriedtoReachGrapes) { |
| 47 | + return ` |
| 48 | + The fox has ${fox.hasReachedGrapes ? '' : 'not '} reached |
| 49 | + the grapes after ${ fox.attemptsMade } |
| 50 | + attempt${ fox.attemptsMade === 1 ? '' : 's' }. |
| 51 | + `; |
| 52 | + } else { |
| 53 | + return `The fox has not tried to reach the grapes yet.`; |
| 54 | + } |
| 55 | + }, |
| 56 | + |
| 57 | + displayResult: function() { |
| 58 | + let result = ` |
| 59 | + ${ this.getTriedText() } |
| 60 | + He feels ${ fox.feelings.join(' and ') } |
| 61 | + and thinks the grapes are ${ grapes.qualities.join(' and ') }. |
| 62 | + ` |
| 63 | + // Trim whitespace so it shows up more nicely in console |
| 64 | + result = result.replace(/(\s+)/g, ' ').trim(); |
| 65 | + return result |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +// Pretty output |
| 70 | +console.log('Before') |
| 71 | +console.log(fox.displayResult()) |
| 72 | +fox.tryToEatGrapes(); |
| 73 | +console.log('After') |
| 74 | +console.log(fox.displayResult()) |
| 75 | + |
| 76 | +// Raw object output |
| 77 | +console.log('fox', fox); |
| 78 | +console.log('grapes', grapes); |
0 commit comments