necessary-utils-core
Version:
Necessary utils for the NodeJS projects.
345 lines (271 loc) • 8.95 kB
JavaScript
// TODO?: Add a summary
class DictionaryItem {
constructor(key, value) {
this.Key = key;
this.Value = value;
}
toJSON() {
return JSON.stringify(this);
}
} // TODO?: Add a summary
class Dictionary extends Array {
constructor() {
super();
} // TODO?: Add a summary
add(key, value) {
return super.push(new DictionaryItem(key, value));
} // TODO?: Add a summary
getValue(objectKey) {
var _a;
return (_a = super.find(x => x.Key === objectKey)) === null || _a === void 0 ? void 0 : _a.Value;
} // TODO?: Add a summary
setValue(key, newValue) {
const i = super.findIndex(x => x.Key === key);
if (i == -1) return;
this[i].Value = newValue;
} // TODO?: Add a summary
static fromObject(obj) {
var _a;
if (typeof obj === "string") throw new Error("Data cannot be returned from a String type.");
if (typeof obj === "number") throw new Error("Data cannot be returned from a Number type.");
if (typeof obj === "boolean") throw new Error("Data cannot be returned from a Boolean type.");
const keys = Object.keys(obj);
if (keys.length === 0) throw new Error("Object is empty.");
let result = new Dictionary();
for (let i in keys) {
const value = (_a = Object.values(obj)[i]) !== null && _a !== void 0 ? _a : null;
result.add(keys[i], value);
}
return result;
} // TODO?: Add a summary
toValueList() {
return this.map(x => x.Value);
} // TODO?: Add a summary
toKeyList() {
return this.map(x => x.Key);
}
}
var Material;
(function (Material) {
class Replacer {
// TODO?: Add a summary
static ReplaceTRCharsToEN(source) {
return source.replace(/\Ğ/, "G").replace(/\Ü/g, "U").replace(/\Ş/g, "S").replace(/\İ/g, "I").replace(/\Ö/g, "O").replace(/\Ç/g, "C").replace(/\ğ/g, "g").replace(/\ü/g, "u").replace(/\ş/g, "s").replace(/\ı/g, "i").replace(/\ö/g, "o").replace(/\ç/g, "c");
}
}
Material.Replacer = Replacer;
})(Material || (Material = {}));
var RegularExpression;
(function (RegularExpression) {
class Validation {} // TODO?: Add a summary
Validation.Email = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
RegularExpression.Validation = Validation;
})(RegularExpression || (RegularExpression = {}));
// TODO?: Add a summary
class UUID {
static V4() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == "x" ? r : r & 0x3 | 0x8;
return v.toString(16);
});
}
}
/**
* ## StopWatch
* This class generates a stopwatch so you can find out how long it takes to complete any given action.
* You can start, stop, restart and resume this stopwatch at any time.
*/
class StopWatch {
constructor() {
this.startTime = null;
this.endTime = null;
}
/**
* This method returns the total elapsed time by milliseconds.
* It returns a 0 value if the stopwatch already never started.
*/
get elapsedTime() {
if (this.startTime === null || this.endTime === null) return 0;
return this.endTime - this.startTime;
}
/**
* This method is used to start the stopwatch.
*/
Start() {
this.startTime = Date.now();
}
/**
* This method stops the stopwatch and returns the total elapsed time by milliseconds.
* However, the elapsed time is not reset.
* @returns Total Elapsed Time
*/
Stop() {
if (this.startTime === null) throw new Error("Watch cannot stopped.");
this.endTime = Date.now();
return this.elapsedTime;
}
/**
* This method stops the stopwatch.
* Also, it stops the stopwatch, if the stopwatch currently is running.
*/
Reset() {
this.startTime = null;
this.endTime = null;
}
/**
* This method resumes your stopwatch.
*/
Resume() {
this.endTime = null;
}
}
/**
* ## TimeSpan
* Also, this class helps you generate the millisecond values you need.
*/
class TimeSpan {
constructor(hour = 0, minute = 0, second = 0, millisecond = 0) {
this._hour = 0;
this._minute = 0;
this._second = 0;
this._millisecond = 0;
this.Hour = hour;
this.Minute = minute;
this.Second = second;
this.Millisecond = millisecond;
}
get Hour() {
return this._hour;
}
set Hour(value) {
if (value >= 0) {
this._hour = value;
return;
}
throw new Error("Hour value cannot be negative.");
}
get Minute() {
return this._minute;
}
set Minute(value) {
if (value >= 0) {
this._minute = value;
return;
}
throw new Error("Minute value cannot be negative.");
}
get Second() {
return this._second;
}
set Second(value) {
if (value >= 0) {
this._second = value;
return;
}
throw new Error("Second value cannot be negative.");
}
get Millisecond() {
return this._millisecond;
}
set Millisecond(value) {
if (value >= 0) {
this._millisecond = value;
return;
}
throw new Error("Millisecond value cannot be negative.");
} // TODO?: Add a summary
Ticks() {
return TimeSpan.FromHour(this.Hour) + TimeSpan.FromMinute(this.Minute) + TimeSpan.FromSecond(this.Second) + this.Millisecond;
} // TODO?: Add a summary
SetToDate(date) {
date.setHours(this.Hour);
date.setMinutes(this.Minute);
date.setSeconds(this.Second);
date.setMilliseconds(this.Millisecond);
return date;
}
static FromSecond(seconds) {
return seconds * 1000;
}
static FromMinute(minutes) {
return minutes * 60 * 1000;
}
static FromHour(hours) {
return hours * 60 * 60 * 1000;
}
static FromDay(days) {
return days * 24 * 60 * 60 * 1000;
}
static FromWeek(days) {
return days * 7 * 24 * 60 * 60 * 1000;
}
}
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
class Timing {
/**
* ## Sleep
* This static method allows you to wait a certain amount of time with the async/await method.
* @param ms
* @example await Wait(1000) | await Wait(TimeSpan.FromSeconds(1))
* @example
* doSomething...
* await Timing.Wait(TimeSpan.FromMinute(1))
* continue...
*/
static Sleep(ms) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => setTimeout(resolve, ms));
});
}
}
/**
* ## CancellationWork
* This static method allows a job to be done only once, within a period of time you specify.
* For example, you produce a console output every time a character is entered into the input box.
* But you want to produce results when the user is no longer entering data for a second.
* You can use `CancellationWork` for this and similar operations.
* @static
* @param callback : CancellationWorkCallback
* @example
*
* import { Timing } from "necessary-utils-core";
*
* const work = () => {
* console.log("Hello.");
* };
* Timing.CancellationWork(work, 1000);
* Timing.CancellationWork(work, 1000);
* Timing.CancellationWork(work, 1000);
* Timing.CancellationWork(work, 1000);
* Timing.CancellationWork(work, 1000);
* // Output : Hello. One time.
*/
Timing.CancellationWork = function () {
let timer;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
}();
export { Dictionary, Material, RegularExpression, StopWatch, TimeSpan, Timing, UUID };