/** * File: app/helper.js * Author: Gerrit Linnemann * * Swiss-knife. */ // load the things we need var logger = require('./logging') , jsonlint = require("jsonlint"); exports.init = function(express) { return this; } exports.timeSince = function(date) { var seconds = Math.floor((new Date() - date) / 1000); var interval = Math.floor(seconds / 31536000); if (interval > 1) { return interval + " years"; } interval = Math.floor(seconds / 2592000); if (interval > 1) { return interval + " months"; } interval = Math.floor(seconds / 86400); if (interval > 1) { return interval + " days"; } interval = Math.floor(seconds / 3600); if (interval > 1) { return interval + " hours"; } interval = Math.floor(seconds / 60); if (interval > 1) { return interval + " minutes"; } return Math.floor(seconds) + " seconds"; } exports.isOlderThanXMinutes = function(date, minutes) { var seconds = Math.floor((new Date() - date) / 1000) interval = seconds / 60 return interval > minutes } exports.dayOfYear = function() { var now = new Date(); var start = new Date(now.getFullYear(), 0, 0); var diff = now - start; var oneDay = 1000 * 60 * 60 * 24; var day = Math.floor(diff / oneDay); logger.trace('Helper | day of year: ' + day); return day; } exports.isJSON = function(jsonString) { try { return jsonlint.parse(jsonString) } catch (e) { if(logger.isDebug()) { logger.error(e.message) //logger.inspect('Error checking JSON', e) } } return false; } exports.isArray = function(toCheck) { return (Object.prototype.toString.call( toCheck ) === '[object Array]'); } exports.isDefinedAndNotNull = function(toCheck) { return ( typeof toCheck !== 'undefined' && toCheck != null ); } exports.getRandomInt = function(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } exports.bytesToSize = function(bytes, precision){ var kilobyte = 1024; var megabyte = kilobyte * 1024; var gigabyte = megabyte * 1024; var terabyte = gigabyte * 1024; if ((bytes >= 0) && (bytes < kilobyte)) { return bytes + ' B'; } else if ((bytes >= kilobyte) && (bytes < megabyte)) { return (bytes / kilobyte).toFixed(precision) + ' KB'; } else if ((bytes >= megabyte) && (bytes < gigabyte)) { return (bytes / megabyte).toFixed(precision) + ' MB'; } else if ((bytes >= gigabyte) && (bytes < terabyte)) { return (bytes / gigabyte).toFixed(precision) + ' GB'; } else if (bytes >= terabyte) { return (bytes / terabyte).toFixed(precision) + ' TB'; } else { return bytes + ' B'; } } /* private */ function bytesToGB(bytes, precision) { var kilobyte = 1024; var megabyte = kilobyte * 1024; var gigabyte = megabyte * 1024; var terabyte = gigabyte * 1024; return (bytes / gigabyte).toFixed(precision); } /* private */ function bytesToMB(bytes, precision) { var kilobyte = 1024; var megabyte = kilobyte * 1024; var gigabyte = megabyte * 1024; var terabyte = gigabyte * 1024; return (bytes / megabyte).toFixed(precision); }