For this project, we are going to create a simple class called Sablier
(hourglass in French), that takes a date and returns it in milliseconds.
In it we will emulate some of Moment
's cool features such as outputting Moment<date>
when logged, function chaining or importing isMoment
as a stand alone function.
Features:
import sablier from "./sablier.js"
import { isSablier } from "./sablier.js"
- No need to use the
new
keyword to instantiate - Can pass an unlimited number of arguments
- With function chaining
-
console.log(sablier(params))
outputs a custom stringSablier<date_in_ms)>
-
${sablier(params)}
outputs a custom stringdate_in_ms
// Custom console.log
// Deno: https://doc.deno.land/builtin/stable#Deno.inspect
const inspect = Symbol.for("Deno.customInspect")
// Node: https://nodejs.org/api/util.html#util_util_inspect_custom
// const inspect = Symbol.for('nodejs.util.inspect.custom');
class Sablier {
constructor(date = new Date(), options) {
// Set the class's properties
this._date = date;
this._options = options;
// Run initialization tasks
this.initialize();
}
initialize() {
// if Date, convert time to milliseconds
if (this._date instanceof Date) {
this._date = this._date.getTime();
}
}
// Output the result
format() {
return this._date;
}
// Chainable function
add(amount) {
this._date += amount;
return this;
}
// Output all the parameters passed after the first one
options() {
return this._options;
}
// Custom console.log
[inspect]() {
return `Sablier<${this._date}>`;
}
// Custom String output
toString() {
return `${this._date}`;
}
}
// Automatically instantiate class
const sablier = (date, ...options) => {
return new Sablier(date, options);
}
// Stand-alone function
const isSablier = date => date instanceof Sablier;
// Access the stand-alone function from the Sablier instance
sablier.isSablier = date => isSablier(date);
export default sablier;
export { isSablier };
Link to live example: https://replit.com/@RilDev/ModernES6Class
Latest comments (0)