r3bl-ts-utils
Version:
The `r3bl-ts-utils` package is a set of useful TypeScript functions and classes that can be used in Node.js and browser environments. They are inspired by Kotlin stdlib, and Rust to write code as expressions rather than statements, colorized text, powerfu
139 lines • 5.23 kB
JavaScript
"use strict";
/*
* Copyright (c) 2022 R3BL LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimerImpl = exports.NoDuration = void 0;
const kotlin_lang_utils_1 = require("../lang-utils/kotlin-lang-utils");
const rust_lang_utils_1 = require("../lang-utils/rust-lang-utils");
const timer_reducer_1 = require("./timer-reducer");
// Constants.
const DEBUG = false;
exports.NoDuration = -1;
class TimerImpl {
name;
delayMs;
durationMs;
counter;
// Properties (simple).
/**
* Node.js uses Timeout and browser uses number. ReturnType<typeof setTimeout> handles this 🎉.
*
* More info:
* - https://tinyurl.com/y2bssbfr
* - https://stackoverflow.com/a/56970244/2085356
* @private
*/
timerHandle;
// Properties (backing fields for getters, setters).
_state;
_onTickFn = rust_lang_utils_1.Option.none();
_onStopFn = rust_lang_utils_1.Option.none();
_onStartFn = rust_lang_utils_1.Option.none();
constructor(name, delayMs, durationMs = exports.NoDuration, counter) {
this.name = name;
this.delayMs = delayMs;
this.durationMs = durationMs;
this.counter = counter;
this._state = this.dispatch(); // Initialize the state.
}
// Getter and setter for onStop.
getOnStopFn() {
return this._onStopFn;
}
setOnStopFn(fn) {
this._onStopFn = rust_lang_utils_1.Option.create(fn);
}
// Getter and setter for onStart.
getOnStartFn() {
return this._onStartFn;
}
setOnStartFn(value) {
this._onStartFn = rust_lang_utils_1.Option.create(value);
}
// Getter and setter for onTick.
getOnTickFn() {
return this._onTickFn;
}
setOnTickFn(fn) {
this._onTickFn = rust_lang_utils_1.Option.create(fn);
}
// State management delegated to TimerReducer.
/**
* Computes the new state using `TimerReducer.reducerFn` and puts it `this.state` property.
* @param action if not provided compute initial state, else use it to get new state
* @return new state object
*/
dispatch = (action) => (0, kotlin_lang_utils_1._also)((0, timer_reducer_1.reducerFn)(this, this.state, action), (newState) => {
this._state = newState;
});
startTicking = () => {
this.dispatch({ type: "start", startTime: Date.now() });
return this;
};
stopTicking = () => {
this.dispatch({ type: "stop", stopTime: Date.now() });
return this;
};
// Getters for state.
get isStopped() {
return this.state.runtimeStatus === "stopped";
}
get isRunning() {
return this.state.runtimeStatus === "running";
}
get isCreatedAndNotStarted() {
return this.state.runtimeStatus === "created_not_started";
}
get state() {
return this._state;
}
// Logic to start / stop the timer.
actuallyStart = () => {
const { name, durationMs, state, counter, delayMs } = this;
DEBUG && console.log(name ?? "Timer", "start called, timerHandle = ", this.timerHandle);
const doTickAndAutoStopCheck = () => {
if (durationMs > 0 && Date.now() - state.startTime >= durationMs) {
this.stopTicking();
}
else {
(0, rust_lang_utils_1._callIfSome)(this._onTickFn, (fn) => fn(this));
counter?.increment();
}
};
this.timerHandle = setInterval(doTickAndAutoStopCheck, delayMs);
(0, rust_lang_utils_1._callIfSome)(this._onStartFn, (fn) => fn(this));
DEBUG && console.log(name ?? "Timer", "started, timerHandle = ", this.timerHandle);
};
actuallyStop = () => {
const { name } = this;
DEBUG && console.log(name ?? "Timer", "stop called, timerHandle = ", this.timerHandle);
if (this.timerHandle) {
// eslint-disable-next-line
clearInterval(this.timerHandle); // Node.js uses Timeout and browser uses number.
this.timerHandle = undefined;
}
(0, rust_lang_utils_1._callIfSome)(this._onStopFn, (fn) => fn(this));
DEBUG && console.log(name ?? "Timer", "stopped, timerHandle = ", this.timerHandle);
};
// Misc methods.
toString = () => {
const { counter, delayMs, name, state, durationMs } = this;
return `name: '${name}', delay: ${delayMs}ms, ${durationMs !== exports.NoDuration ? `duration:${durationMs}ms` : ""} counter:${counter ? counter.value : "n/a"}, state:${state.runtimeStatus}`;
};
}
exports.TimerImpl = TimerImpl;
//# sourceMappingURL=timer-impl.js.map