UNPKG

promise-dedup

Version:
35 lines (34 loc) 1.13 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.dedup = exports.cache = void 0; var fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify")); exports.cache = new Map(); function dedup(exec, key, stale) { if (stale === void 0) { stale = "settled"; } var strKey = (0, fast_json_stable_stringify_1.default)(key); var cached = exports.cache.get(strKey); if (cached) return cached; var promise = exec(); exports.cache.set(strKey, promise); var clean = function () { exports.cache.delete(strKey); }; if (typeof stale === "number") { setTimeout(clean, stale); } else if (stale === "settled") { promise = promise.then(function (value) { clean(); return value; }, function (error) { clean(); throw error; }); } return promise; } exports.dedup = dedup;