Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# deverything

## 4.9.0

### Minor Changes

- singleton

## 4.8.0

### Minor Changes
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "deverything",
"version": "4.8.0",
"version": "4.9.0",
"description": "Everything you need for Dev",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
Expand Down
40 changes: 40 additions & 0 deletions src/helpers/singleton.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { isPromise } from "../validators/isPromise";

/**
* Creates a lazily-initialized singleton from a factory function.
* Works with both sync and async factories — the return type mirrors the factory's.
*
* For async factories, concurrent callers during initialization share the same
* in-flight promise rather than triggering multiple factory calls. If the promise
* rejects, the singleton resets so the next call retries.
*/
export const singleton = <Result>(factory: () => Result): (() => Result) => {
let hasInstance = false;
let instance!: Result;

return () => {
if (hasInstance) {
return instance;
}

const result = factory();

if (isPromise(result)) {
hasInstance = true;
instance = result.then(
(value) => value,
(error) => {
hasInstance = false;
throw error;
}
) as Result;

return instance;
}

// not a promise
hasInstance = true;
instance = result;
return result;
};
};