X-Git-Url: http://git.squeep.com/?a=blobdiff_plain;f=src%2Fcommon.js;h=4ed310f44ebb4d524c58385ad76a4c2d25b88375;hb=43898cdd317a127bc45e8b3cb2f160df386760a1;hp=b82b13e35e9b2fbf8224b8ee6407b5e3076ac9a9;hpb=9696c012e6b9a6c58904baa397ca0ebf78112316;p=websub-hub diff --git a/src/common.js b/src/common.js index b82b13e..4ed310f 100644 --- a/src/common.js +++ b/src/common.js @@ -26,6 +26,22 @@ const validHash = (algorithm) => getHashes() .filter((h) => h.match(/^sha[0-9]+$/)) .includes(algorithm); + +/** + * Return an array containing x if x is not an array. + * @param {*} x + */ +const ensureArray = (x) => { + if (x === undefined) { + return []; + } + if (!Array.isArray(x)) { + return Array(x); + } + return x; +}; + + /** * Recursively freeze an object. * @param {Object} o @@ -41,7 +57,7 @@ const freezeDeep = (o) => { } }); return o; -} +}; /** @@ -84,7 +100,7 @@ const topicLeaseDefaults = () => { * @param {Number} jitter * @returns {Number} */ - const attemptRetrySeconds = (attempt, retryBackoffSeconds = [60, 120, 360, 1440, 7200, 43200, 86400], jitter = 0.618) => { +const attemptRetrySeconds = (attempt, retryBackoffSeconds = [60, 120, 360, 1440, 7200, 43200, 86400], jitter = 0.618) => { const maxAttempt = retryBackoffSeconds.length - 1; if (typeof attempt !== 'number' || attempt < 0) { attempt = 0; @@ -95,7 +111,7 @@ const topicLeaseDefaults = () => { let seconds = retryBackoffSeconds[attempt]; seconds += Math.floor(Math.random() * seconds * jitter); return seconds; -} +}; /** @@ -103,10 +119,10 @@ const topicLeaseDefaults = () => { * @param {Array} array * @param {Number} per */ - const arrayChunk = (array, per = 1) => { +const arrayChunk = (array, per = 1) => { const nChunks = Math.ceil(array.length / per); return Array.from(Array(nChunks), (_, i) => array.slice(i * per, (i + 1) * per)); -} +}; /** @@ -114,12 +130,12 @@ const topicLeaseDefaults = () => { * @param {Array} dst * @param {Array} src */ - const stackSafePush = (dst, src) => { +const stackSafePush = (dst, src) => { const jsEngineMaxArguments = 2**16; // Current as of Node 12 arrayChunk(src, jsEngineMaxArguments).forEach((items) => { Array.prototype.push.apply(dst, items); }); -} +}; /** @@ -140,6 +156,7 @@ module.exports = { arrayChunk, attemptRetrySeconds, axiosResponseLogData, + ensureArray, freezeDeep, logTruncate, randomBytesAsync,