UNPKG

cognitive-complexity-ts

Version:

This program analyses TypeScript and JavaScript code according to the [Cognitive Complexity metric](https://www.sonarsource.com/docs/CognitiveComplexity.pdf). It produces a JSON summary and a GUI for exploring the complexity of your codebase.

82 lines 2.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Unreachable = void 0; exports.doesNotThrow = doesNotThrow; exports.keysToAsyncValues = keysToAsyncValues; exports.createObjectOfPromisedValues = createObjectOfPromisedValues; exports.nonNaN = nonNaN; exports.repeat = repeat; async function doesNotThrow(promise) { try { await promise; return true; } catch (err) { return false; } } /** * Builds an object from a list of keys whose values are based on the key itself, * but where that value is produced asynchronously. * * This function starts by spawning a promise to generate the value for each key, * and ends when all values have been produced. * This is faster than spawning promises in sequence. */ async function keysToAsyncValues(keys, toValue) { const output = {}; // Create promises to build the output concurrently. // Each promise has a side effect of adding to the output. const promises = keys.map(async (key) => { output[key] = await toValue(key); }); // Only return when all effects have been applied. await Promise.all(promises); return output; } /** * Builds an object from a list of input items. * The keys and values are derived from the input item, * but the values either need to be generated asynchronously or not at all. */ async function createObjectOfPromisedValues(inputs, toKey, toMaybePromise) { const output = {}; // Create a Promise for each input entry // that may perform another asynchronously task to generate a key-value pair. // If it does so, that key-value pair is assigned to the output. // No key-value will be produced if there is no internal Promise to wait for. const promises = []; for (const input of inputs) { const maybePromise = toMaybePromise(input); if (maybePromise !== undefined) { const promise = maybePromise.then(value => { const key = toKey(input); output[key] = value; }); promises.push(promise); } } // make sure all promises have resolved before returning await Promise.all(promises); return output; } function nonNaN(num, fallback) { if (Number.isNaN(num)) { return fallback; } return num; } function repeat(str, times) { let res = ""; for (let i = 0; i < times; i++) { res += str; } return res; } class Unreachable extends Error { constructor(reason) { super("Unreachable branch.\n" + reason); } } exports.Unreachable = Unreachable; //# sourceMappingURL=util.js.map