88 lines
1.7 KiB
JavaScript
88 lines
1.7 KiB
JavaScript
/*
|
|
* Copyright (C) Sapphirecode - All Rights Reserved
|
|
* This file is part of Utilities which is released under MIT.
|
|
* See file 'LICENSE' for full license details.
|
|
* Created by Timo Hocker <timo@sapphirecode.ovh>, March 2020
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* truncates a floating point number
|
|
*
|
|
* @param {number} num number to truncate
|
|
* @param {number} len length to truncate to
|
|
* @returns {number} truncated number
|
|
*/
|
|
function truncate_decimal (num, len) {
|
|
return Math.round (num * (10 ** len)) / (10 ** len);
|
|
}
|
|
|
|
/**
|
|
* parse json and catch invalid strings
|
|
*
|
|
* @param {string} text input
|
|
* @returns {any} parsed
|
|
*/
|
|
function try_parse_json (text) {
|
|
try {
|
|
return JSON.parse (text);
|
|
}
|
|
catch (e) {
|
|
// noop
|
|
}
|
|
return null;
|
|
}
|
|
|
|
|
|
/**
|
|
* copy an object to prevent modification to the original
|
|
*
|
|
* @param {object} obj object to copy
|
|
* @returns {object} copy
|
|
*/
|
|
function copy_object (obj) {
|
|
return JSON.parse (JSON.stringify (obj));
|
|
}
|
|
|
|
/**
|
|
* run a regular expression and callback for every result
|
|
*
|
|
* @param {any} regex regular expression
|
|
* @param {any} data data to run on
|
|
* @param {any} func function to execute
|
|
*/
|
|
function run_regex (regex, data, func) {
|
|
if (!regex.global) {
|
|
const result = regex.exec (data);
|
|
if (result)
|
|
func (result);
|
|
return;
|
|
}
|
|
let res = regex.exec (data);
|
|
while (res) {
|
|
func (res);
|
|
res = regex.exec (data);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* check if an object is either undefined, null or NaN
|
|
*
|
|
* @param {any} obj object to check
|
|
* @returns {boolean} true if nil
|
|
*/
|
|
function is_nil (obj) {
|
|
return typeof obj === 'undefined'
|
|
|| obj === null
|
|
|| (typeof obj === 'number' && isNaN (obj));
|
|
}
|
|
|
|
module.exports = {
|
|
truncate_decimal,
|
|
try_parse_json,
|
|
copy_object,
|
|
run_regex,
|
|
is_nil
|
|
};
|