1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 10:54:44 +00:00

refactor: change separate tools by category

This commit is contained in:
2025-05-19 17:43:42 +07:00
parent d55737df2f
commit 78fb4da82a
158 changed files with 32 additions and 24 deletions

View File

@@ -0,0 +1,47 @@
import type { MaybePromise } from "../../types";
/**
* @name SyncMutex
* @category Utils
* @description A simple synchronous mutex to provide more readable locking and unlocking of code blocks
*
* @example
* const mutex = new SyncMutex();
*
* mutex.lock();
*
* mutex.unlock();
*
* const result = await mutex.execute(() => {
* // do something
* return Promise.resolve('done');
* });
*
* @since 0.0.5
*/
export class SyncMutex {
private state = false;
public get isLocked() {
return this.state;
}
public lock() {
this.state = true;
}
public unlock() {
this.state = false;
}
public async execute<T>(callback: () => T) {
if (this.isLocked)
return;
this.lock();
const result = await callback();
this.unlock();
return result;
}
}