federer
Version:
Experiments in asynchronous federated learning and decentralized learning
96 lines • 3.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.partition = exports.cumulativeSum = exports.intersection = exports.isEmpty = exports.chunk = exports.zip = exports.clamp = exports.range = exports.convertBufferToArrayBuffer = void 0;
const assert = require("assert");
function convertBufferToArrayBuffer(buffer) {
// https://stackoverflow.com/a/31394257/918389
return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
}
exports.convertBufferToArrayBuffer = convertBufferToArrayBuffer;
/**
* Creates an array that contains numbers between `start` and `end`.
*
* @param start First number of the range (inclusive)
* @param end Last number of the range (inclusive)
*/
function range(start, end) {
return new Array(end - start + 1).fill(0).map((_, ind) => ind + start);
}
exports.range = range;
/**
* Clamps a value `x` between `min` and `max`.
*/
function clamp(min, x, max) {
return Math.min(Math.max(min, x), max);
}
exports.clamp = clamp;
/**
* Zips the values of two arrays together into a single array. The length of the
* output is equal to the length of the shortest of the two arrays.
*/
function zip(array1, array2) {
const length = Math.min(array1.length, array2.length);
const res = [];
for (let i = 0; i < length; ++i) {
res.push([array1[i], array2[i]]);
}
return res;
}
exports.zip = zip;
/**
* Groups elements of an array into chunks of the given size. For instance,
* chunking `[1, 2, 3, 4]` into chunks of size 2 returns `[[1, 2], [3, 4]]`.
*/
function chunk(array, size) {
assert(size > 0);
assert.strictEqual(array.length % size, 0, "Chunk size must evenly divide array length");
const result = [];
for (let i = 0; i < array.length; i += size) {
const chunk = array.slice(i, i + size);
result.push(chunk);
}
return result;
}
exports.chunk = chunk;
/**
* Returns whether the given object is an empty object.
* @see {@link https://stackoverflow.com/q/679915/918389}
*/
function isEmpty(obj) {
for (const _ in obj)
return false;
return true;
}
exports.isEmpty = isEmpty;
/**
* Returns the intersection `a ∩ b` of two sets `a` and `b`
*/
function intersection(a, b) {
return new Set([...a.values()].filter((x) => b.has(x)));
}
exports.intersection = intersection;
function cumulativeSum(numbers) {
let sum = 0;
return numbers.map((num) => (sum += num));
}
exports.cumulativeSum = cumulativeSum;
/**
* Partition an array according to a predicate. The items for which the
* predicate is true are in the left position, the items for which the predicate
* is false are in the right position.
*/
function partition(array, predicate) {
const left = [];
const right = [];
for (const item of array) {
if (predicate(item)) {
left.push(item);
}
else {
right.push(item);
}
}
return [left, right];
}
exports.partition = partition;
//# sourceMappingURL=utils.js.map