Created
January 17, 2021 04:42
-
-
Save Classy-Bear/36a393e11453cb46122d9d484d0964a1 to your computer and use it in GitHub Desktop.
Defining an object. Function vs Classes
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
function Stopwatch() { | |
let isStarted = false; | |
let startTime; | |
let stopTime; | |
Object.defineProperty(this, "duration", { | |
get: () => { | |
if(startTime && stopTime) { | |
return (stopTime - startTime) / 1000; | |
} | |
if(startTime) { | |
return (new Date().getTime() - startTime) / 1000; | |
} | |
throw new Error("You haven't initiate the timer."); | |
}, | |
set: () => { | |
throw new Error("You cannot set the duration by yourself."); | |
}, | |
}); | |
this.reset = () => { | |
if (isStarted) { | |
this.stop(); | |
} | |
stopTime = undefined; | |
startTime = undefined; | |
}; | |
this.start = () => { | |
if (!isStarted) { | |
isStarted = true; | |
startTime = new Date().getTime(); | |
} else { | |
throw new Error("This has already started."); | |
} | |
}; | |
this.stop = () => { | |
if (isStarted) { | |
isStarted = false; | |
stopTime = new Date().getTime(); | |
} else { | |
throw new Error("This has already stopped."); | |
} | |
}; | |
} | |
class StopwatchClass { | |
#isStarted = false; | |
#startTime; | |
#stopTime; | |
constructor() {} | |
get duration() { | |
if(this.#startTime && this.#stopTime) { | |
return (this.#stopTime - this.#startTime) / 1000; | |
} | |
if(startTime) { | |
return (new Date().getTime() - this.#startTime) / 1000; | |
} | |
throw new Error("You haven't initiate the timer."); | |
} | |
set duration(_) { | |
throw new Error("You cannot set the duration by yourself."); | |
} | |
reset() { | |
if (this.#isStarted) { | |
stop(); | |
} else { | |
throw new Error("Cannot reset. This's already stopped."); | |
} | |
this.#stopTime = undefined; | |
this.#startTime = undefined; | |
} | |
start() { | |
if (!this.#isStarted) { | |
this.#isStarted = true; | |
this.#startTime = new Date().getTime(); | |
} else { | |
throw new Error("This has already started."); | |
} | |
} | |
stop() { | |
if (this.#isStarted) { | |
this.#isStarted = false; | |
this.#stopTime = new Date().getTime(); | |
} else { | |
throw new Error("This has already stopped."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment