Last active
November 22, 2017 13:28
-
-
Save garcia556/76d656c1102e720a4cc9d154f9a3eff2 to your computer and use it in GitHub Desktop.
Some helper functions for node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const | |
fs = require("fs"), | |
crypto = require("crypto"), | |
{ promisify } = require("util"); | |
var root = {}; | |
root.clamp = (value, min, max) => { return Math.min(Math.max(value, min), max); }; | |
root.jsonToString = obj => { return JSON.stringify(obj, null, "\t"); } | |
root.errorDump = err => | |
{ | |
if (!err) | |
return ""; | |
let stack = err.stack || null; | |
if (stack) | |
delete err.stack; | |
let result = ""; | |
let str = root.jsonToString(err); | |
if (str != "{}") | |
result += `\n${root.jsonToString(err)}`; | |
if (stack) | |
result += `\nStack:\n${stack}`; | |
return result; | |
} | |
root.writeFileAsync = promisify(fs.writeFile); | |
root.readFileAsync = promisify(fs.readFile); | |
root.readdirAsync = promisify(fs.readdir); | |
root.getFunctionParams = f => { return /\(\s*([^)]+?)\s*\)/.exec(f.toString())[1].split(",").map(s => { return s.trim(); }); } | |
root.md5 = value => { return crypto.createHash("md5").update(value).digest("hex"); } | |
root.getObjectPart = (obj, keys) => | |
{ | |
let res = {}; | |
for (let key of keys) | |
res[key] = obj[key]; | |
return res; | |
} | |
root.shortenString = str => | |
{ | |
str = str || ""; | |
if (str.length > 1024) | |
str = | |
`${str.slice(0, 384)} | |
... | |
... | |
... | |
${str.slice(-384)}`; | |
return str; | |
} | |
root.getSimpleClone = obj => { return JSON.parse(JSON.stringify(obj)); } | |
root.hasOwnValue = (obj, val) => | |
{ | |
for (var prop in obj) | |
if(obj.hasOwnProperty(prop) && obj[prop] === val) | |
return true; | |
return false; | |
} | |
root.isEmpty = obj => | |
{ | |
for (var key in obj) | |
if (obj.hasOwnProperty(key)) | |
return false; | |
return true; | |
}; | |
root.isFunction = func => { return func && func.constructor && func.call && func.apply; }; | |
root.tryParseJSON = function(jsonString) | |
{ | |
try | |
{ | |
var o = JSON.parse(jsonString); | |
if (o && typeof o === "object" && o !== null) | |
return o; | |
} | |
catch (e) { } | |
return false; | |
}; | |
////////////////////////////////////////////////////////////////////// | |
module.exports = root; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment