X-Git-Url: http://git.squeep.com/?a=blobdiff_plain;f=src%2Fcommon.js;h=4ed310f44ebb4d524c58385ad76a4c2d25b88375;hb=HEAD;hp=0cacc3bf086f2b57f0b10db1ef289c6be7961e15;hpb=28de4364128a4b03918a8cbe868009b5d427220a;p=websub-hub diff --git a/src/common.js b/src/common.js index 0cacc3b..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; -} +}; /** @@ -95,7 +111,7 @@ const attemptRetrySeconds = (attempt, retryBackoffSeconds = [60, 120, 360, 1440, let seconds = retryBackoffSeconds[attempt]; seconds += Math.floor(Math.random() * seconds * jitter); return seconds; -} +}; /** @@ -106,7 +122,7 @@ const attemptRetrySeconds = (attempt, retryBackoffSeconds = [60, 120, 360, 1440, 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)); -} +}; /** @@ -119,7 +135,7 @@ const stackSafePush = (dst, src) => { arrayChunk(src, jsEngineMaxArguments).forEach((items) => { Array.prototype.push.apply(dst, items); }); -} +}; /** @@ -140,6 +156,7 @@ module.exports = { arrayChunk, attemptRetrySeconds, axiosResponseLogData, + ensureArray, freezeDeep, logTruncate, randomBytesAsync,