Skip to content

Commit

Permalink
Add ability to set inner instance (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
duart38 authored Dec 3, 2021
1 parent 1706119 commit b54bf26
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,17 @@
![alt text](https://img.shields.io/github/workflow/status/grevend/singleton/Test%20Deno%20module?label=Tests "Tests")

## Example

```typescript
const rand = singleton(Math.random);
const first = rand.getInstance();
const second = rand.getInstance(); // first === second
```

#### Changing the inner instance
```typescript
const str = singleton(() => "a");
const first = rand.getInstance(); // "a"
str.setInstance("b");
const second = rand.getInstance(); // "b", first !== second
```
3 changes: 2 additions & 1 deletion mod.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
export type Singleton<I> = { getInstance: () => I };
export type Singleton<I> = { getInstance: () => I; setInstance: (x: I) => I };

export default function singleton<I>(factory: () => I): Singleton<I> {
let instance: I | null = null;
return {
getInstance: () => instance == null ? (instance = factory()) : instance,
setInstance: (x: I) => instance = x,
};
}
2 changes: 2 additions & 0 deletions singleton.bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ function singleton(factory) {
let instance = null;
return {
getInstance: ()=>instance == null ? instance = factory() : instance
,
setInstance: (x)=>instance = x
};
}
export { singleton as default };
7 changes: 7 additions & 0 deletions test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,10 @@ Deno.test("check single instance creation", () => {
const value = rand.getInstance();
assertEquals(value, rand.getInstance());
});

Deno.test("check setting inner instance", () => {
const str = singleton(() => "a");
assertEquals(str.getInstance(), "a");
str.setInstance("b");
assertEquals(str.getInstance(), "b");
});

0 comments on commit b54bf26

Please sign in to comment.