@bothive/helpers
Version:
Collection of helper functions mainly used inside bothive-core project
61 lines • 2.01 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
function getRandomValue(list) {
if (!list.length) {
return "";
}
if (list.length === 1) {
return list[0];
}
const index = Math.floor(Math.random() * list.length);
return list[index];
}
function splitInParts({ batch, size }) {
if (!(batch === null || batch === void 0 ? void 0 : batch.length)) {
return [];
}
const chunkCount = Math.ceil(batch.length / size);
const offset = Math.ceil(batch.length / chunkCount);
const tempArray = new Array(chunkCount);
return [...tempArray].map((_, index) => batch.slice(offset * index, offset * (index + 1)));
}
function splitInChunks({ batch, chunkSize }) {
const batchSize = calculateByteSize(batch);
if (!batchSize) {
return [];
}
const chunkCount = Math.ceil(batchSize / chunkSize);
const offset = batch.length / chunkCount;
const tempArray = new Array(chunkCount);
return [...tempArray].reduce((prev, _, index) => {
const chunk = batch.slice(offset * index, offset * (index + 1));
const size = calculateByteSize(chunk);
if (Math.ceil(size / chunkSize) > 1 && chunk.length > 1) {
const saveChunk = splitInChunks({ batch: chunk, chunkSize });
return [...prev, ...saveChunk];
}
return [...prev, chunk];
}, []);
}
function calculateByteSize(payload) {
if (!payload) {
return 0;
}
const stringPayload = JSON.stringify(payload);
const data = Buffer.from(stringPayload).toString("base64");
return data.length;
}
function sortArrayByKey({ batch, key, }) {
if (!batch || !key) {
throw new Array("Batch or key is undefined");
}
return batch.sort((a, b) => new Date(a[key]).getTime() - new Date(b[key]).getTime());
}
exports.default = {
getRandomValue,
splitInParts,
splitInChunks,
calculateByteSize,
sortArrayByKey,
};
//# sourceMappingURL=array.helpers.js.map