utilities/index.js

91 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2020-03-04 12:13:28 +01:00
/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of utilities which is released under MIT.
2020-03-25 17:01:22 +01:00
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, May 2020
2020-03-04 12:13:28 +01:00
*/
'use strict';
2020-11-05 07:50:27 +01:00
const recursive_filter = require ('./filter');
2020-03-04 12:13:28 +01:00
/**
* 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;
}
2020-03-10 10:46:12 +01:00
/**
* 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));
}
2020-03-30 11:00:52 +02:00
/**
* run a regular expression and callback for every result
*
2020-03-30 11:01:51 +02:00
* @param {any} regex regular expression
* @param {any} data data to run on
* @param {any} func function to execute
2020-03-30 11:00:52 +02:00
*/
function run_regex (regex, data, func) {
2020-03-30 11:21:05 +02:00
if (!regex.global) {
const result = regex.exec (data);
if (result)
func (result);
return;
}
2020-03-30 11:00:52 +02:00
let res = regex.exec (data);
while (res) {
func (res);
res = regex.exec (data);
}
}
2020-04-27 12:40:54 +02:00
/**
* 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));
}
2020-03-30 11:00:52 +02:00
2020-03-04 12:13:28 +01:00
module.exports = {
truncate_decimal,
2020-03-10 10:46:12 +01:00
try_parse_json,
2020-03-30 11:00:52 +02:00
copy_object,
2020-04-27 12:40:54 +02:00
run_regex,
2020-06-08 14:44:09 +02:00
is_nil,
recursive_filter
2020-03-04 12:13:28 +01:00
};