Skip to content

Instantly share code, notes, and snippets.

View ztrehagem's full-sized avatar
🥳

SUWA Shigeki ztrehagem

🥳
View GitHub Profile
type Task<T> = () => Promise<T>;
export class TaskPool {
#isReady: boolean;
#current: Task<unknown> | null;
readonly #queue: Task<unknown>[];
constructor(
params: {
readonly isReady?: boolean;
@ztrehagem
ztrehagem / KeyPath.ts
Last active September 26, 2023 01:58
export class KeyPath<T extends string = string> {
#_brand!: never;
readonly #path: readonly string[];
constructor(path: T) {
this.#path = path.split(".");
}
of<Expected>(object: unknown): Expected {
interface ReadonlyMapConstructor {
new <K, V>(entries?: IterableIterator<[K, V]> | null): ReadonlyMap<K, V>;
}
class ReadonlyMapClass<K, V> extends Map<K, V> {}
export const ReadonlyMap: ReadonlyMapConstructor = ReadonlyMapClass;
//
interface Action<T, U = unknown> {
act: (state: T) => Promise<U>;
deriveActual: (state: T, actResult: U) => T;
deriveOptimistic: (state: T) => T;
}
export class OptimisticStore<T> {
#optimisticState: T;
#committedState: T;
readonly #runner = new SerialTaskRunner();
declare const historyIdBrand: unique symbol;
let historyId = 0;
type HistoryId = number & { [historyIdBrand]: never };
interface HistoryItem<T, A> {
readonly id: HistoryId;
readonly action: A;
readonly state: T;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const debounce = <T extends (...args: any[]) => void>(
fn: T,
timeout: number,
): T => {
let timeoutId: number | undefined;
return new Proxy(fn, {
apply: (target, thisArg, args) => {
window.clearInterval(timeoutId);
interface DetailedResponse<Status extends number, Body> extends Response {
status: Status;
json: () => Promise<Body>;
}
interface DetailedRequest<ExpectedResponse extends Response> extends Request {}
type DetailedFetch = <Req extends DetailedRequest<Res>, Res extends Response = Req extends DetailedRequest<infer U> ? U : never>(request: Req, init?: RequestInit) => Promise<Res>;
const detailedFetch = fetch as DetailedFetch;
type Hash = string | number | symbol | object;
interface Hashable<K extends Hash> {
readonly hash: K;
}
class FooId implements Hashable<number> {
readonly primitive: number;
constructor(primitive: number) {
export const uniqueArray = <E>(
array: readonly E[],
isEqual: (a: E, b: E) => boolean = Object.is
): E[] => {
return array.filter(
(a, index, self) => index == self.findIndex((b) => isEqual(a, b))
);
};
@ztrehagem
ztrehagem / DetectCircularDepencies.js
Last active April 12, 2023 01:56
有向グラフの閉路を見つけるJS
/** @type {Map<string, Set<string>>} */
const dependencyMap = /* provide source */;
/** @type {Set<string>} */
const searched = new Set();
/**
* @param {string} target
* @param {string[]} path
*/