Created
December 15, 2017 20:52
-
-
Save thinkjson/32f2e5be63f7dfbde0e2fab0da0b6fbb to your computer and use it in GitHub Desktop.
Having a little too much fun with typescript, ES6 Promises, and arrow functions
This file contains hidden or 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
| class Person { | |
| private lifespan: number; | |
| private life: number; | |
| private YEAR_IN_SECONDS: number = 100; | |
| constructor(public name: string, public age: number) { | |
| this.lifespan = Math.floor(Math.random() * 40 + 60); | |
| } | |
| liveLife = () => { | |
| return new Promise<number>((resolve, reject) => { | |
| if (this.age <= this.lifespan) { | |
| this.life = setInterval(() => { | |
| this.age++; | |
| console.log(`${this.name} is now ${this.age} years old!`); | |
| if (this.age > this.lifespan) { | |
| console.log(`I regret to inform you that ${this.name} has died.`); | |
| resolve(this.age); | |
| clearInterval(this.life); | |
| } | |
| }, this.YEAR_IN_SECONDS); | |
| } else { | |
| console.log('Reincarnation is not a thing in this program. ' + | |
| 'Please make a new Person.'); | |
| reject(this.age); | |
| } | |
| }); | |
| } | |
| } | |
| let bob = new Person('Bob', 45); | |
| let life = bob.liveLife() | |
| .then((age) => { | |
| console.log(`${bob.name} lived to the ripe old age of ${age}`); | |
| bob.liveLife() | |
| .catch(err => {}); | |
| }); |
This file contains hidden or 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
| Bob is now 46 years old! | |
| Bob is now 47 years old! | |
| Bob is now 48 years old! | |
| Bob is now 49 years old! | |
| Bob is now 50 years old! | |
| Bob is now 51 years old! | |
| Bob is now 52 years old! | |
| Bob is now 53 years old! | |
| Bob is now 54 years old! | |
| Bob is now 55 years old! | |
| Bob is now 56 years old! | |
| Bob is now 57 years old! | |
| Bob is now 58 years old! | |
| Bob is now 59 years old! | |
| Bob is now 60 years old! | |
| Bob is now 61 years old! | |
| Bob is now 62 years old! | |
| Bob is now 63 years old! | |
| Bob is now 64 years old! | |
| Bob is now 65 years old! | |
| Bob is now 66 years old! | |
| Bob is now 67 years old! | |
| I regret to inform you that Bob has died. | |
| Bob lived to the ripe old age of 67 | |
| Reincarnation is not a thing in this program. Please make a new Person. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment