what-to-play
Version:
Score aggregator for lists of games
103 lines • 2.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.printable = exports.nonNaN = exports.limitConcurrent = exports.escapeDoubleQuotes = exports.csvFriendly = exports.bug = exports.bindUndefined = exports.average = void 0;
const assert_1 = require("assert");
function average(arr) {
let total = 0;
const len = arr.length;
for (let i = 0; i < len; i++) {
total += arr[i];
}
return total / len;
}
exports.average = average;
function bindUndefined(val, func) {
if (val === undefined)
return undefined;
return func(val);
}
exports.bindUndefined = bindUndefined;
function bug() {
(0, assert_1.fail)("bug");
}
exports.bug = bug;
function csvFriendly(s) {
// if no special characters, it's fine as is
if (!s.includes(",") && !s.includes("\n") && !s.includes('"')) {
return s;
}
// special characters are only allowed inside double quotes
s = escapeDoubleQuotes(s, '""');
return `"${s}"`;
}
exports.csvFriendly = csvFriendly;
const allDoubleQuotes = /"/g;
function escapeDoubleQuotes(s, replacement) {
return s.replace(allDoubleQuotes, replacement);
}
exports.escapeDoubleQuotes = escapeDoubleQuotes;
/**
* @param num Number of calls to the given function that can be spawned
* (i.e. waiting to resolve) at once.
* @param func The function to limit
*/
function limitConcurrent(num, func) {
let concurrent = 0;
const waiting = [];
const call = (...args) => {
concurrent += 1;
const prom = func(...args);
prom.finally(() => {
concurrent -= 1;
next();
});
return prom;
};
const next = () => {
if (concurrent < num) {
const nextFunc = waiting.shift();
if (nextFunc === undefined)
return;
nextFunc();
}
};
const limitedFunc = (...args) => {
// call the function immediately
if (concurrent < num) {
return call(...args);
}
// delay calling the function
// return a promise that resolves when the actual promise resolves
// but put the function to spawn the actual promise in a queue
// instead of spawning it
return new Promise((resolve, reject) => {
const funcForLater = async () => {
try {
resolve(await call(...args));
}
catch (err) {
reject(err);
}
};
waiting.push(funcForLater);
});
};
return limitedFunc;
}
exports.limitConcurrent = limitConcurrent;
function nonNaN(num, fallback) {
if (Number.isNaN(num)) {
return fallback;
}
else {
return num;
}
}
exports.nonNaN = nonNaN;
function printable(val) {
if (val === undefined)
return "";
return val.toString();
}
exports.printable = printable;
//# sourceMappingURL=util.js.map