@dpaskhin/unique
Version:
Ensures unique values by rejecting duplicates.
87 lines (85 loc) • 2.87 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: !0 });
}, __copyProps = (to, from, except, desc) => {
if (from && typeof from == "object" || typeof from == "function")
for (let key of __getOwnPropNames(from))
!__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
// src/main/index.ts
var main_exports = {};
__export(main_exports, {
GLOBAL_STORE: () => GLOBAL_STORE,
unique: () => unique,
uniqueFactory: () => uniqueFactory
});
module.exports = __toCommonJS(main_exports);
function uniqueFactory(fn, options = {}) {
let {
store = /* @__PURE__ */ new Set(),
maxRetries = 50,
maxTime = 50,
exclude = [],
stringifier = JSON.stringify
} = options;
return exclude = exclude.map((value) => stringifier(value)), function(...args) {
let result, currentIterations = 0, startTime = Date.now();
for (; ; ) {
let duration = Date.now() - startTime;
if (duration >= maxTime)
throw new UniqueError(
`Exceeded maxTime (${maxTime})`,
store.size,
duration,
currentIterations
);
if (currentIterations >= maxRetries)
throw new UniqueError(
`Exceeded maxTries (${maxRetries})`,
store.size,
duration,
currentIterations
);
result = fn.apply(null, args);
let tmpResult = stringifier(result);
if (currentIterations++, !store.has(tmpResult) && !exclude.includes(tmpResult)) {
store.add(tmpResult);
break;
}
}
return result;
};
}
var GLOBAL_STORE = /* @__PURE__ */ new Set();
function unique(fnOrValue, argsOrOptions, options = {}) {
return typeof fnOrValue == "function" ? uniqueFactory(
fnOrValue,
Object.assign({}, options, { store: options.store || GLOBAL_STORE })
).apply(null, argsOrOptions || []) : uniqueFactory(
() => fnOrValue,
Object.assign({}, argsOrOptions || (argsOrOptions = {}), {
store: argsOrOptions.store || GLOBAL_STORE,
maxRetries: 1
})
)();
}
var UniqueError = class extends Error {
constructor(code, size, duration, iterations) {
super(
`${code} - store size: ${size}, retried: ${iterations}, duration: ${duration}ms`
), this.name = "UniqueError";
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GLOBAL_STORE,
unique,
uniqueFactory
});