Skip to content

Instantly share code, notes, and snippets.

View DScheglov's full-sized avatar
🏠
Working from home

Dmytro Shchehlov DScheglov

🏠
Working from home
View GitHub Profile
@DScheglov
DScheglov / index.ts
Created April 15, 2025 20:54
Floating Window Average
class FixedSizeBuffer<T> {
#buffer: T[];
#maxSize: number;
#index: number = 0;
#count: number = 0;
static of<T>(size: number) {
return new FixedSizeBuffer<T>(size);
}
@DScheglov
DScheglov / average-of-last-n-ukr.md
Created April 14, 2025 16:57
Середнє останніх N

Середнє останніх N

Сервер отримує послідовність запитів. Кожен запит — це дійсне число, результат обчислення. Після кожного запиту потрібно повертати середнє значення останніх не більше ніж N чисел.

Вхідні дані

Перший рядок містить одне ціле число N (1 ≤ N ≤ 10⁵) — максимальна кількість останніх значень, які враховуються при обчисленні середнього.

Другий рядок містить одне ціле число Q (1 ≤ Q ≤ 10⁵) — кількість запитів.

@DScheglov
DScheglov / retry-fetch.ts
Created March 27, 2025 14:15
Retry-decorator for fetch
type ShouldRetryFn = (err: unknown, res: Response | undefined) => boolean
export class RetryFetchError extends TypeError {
name = "RetryFetchError"
constructor(maxAttempts: number, cause?: unknown) {
super(`Failed to fetch after ${maxAttempts} attempts.`, { cause });
if (!Object.prototype.hasOwnProperty.call(this, "cause")) {
Object.defineProperty(this, "cause", { value: cause })
}
}
@DScheglov
DScheglov / gof-state-pattern.ts
Created March 24, 2025 15:03
GoF State Pattern
/**
* TaxiOrder:
* - **Draft** (default) the order is created with empty data
* - Placed - the order is placed and System is searching for Driver
* - Accepted - the Driver accepted the Order, but the the trip is not yet started
* - InProgress - the trip is started but not finished
* - Completed - the trip is ended
* - Cancelled - the Order has been cancelled by Driver or by Customer
*/
@DScheglov
DScheglov / props-resolver.ts
Created March 3, 2023 18:51
propsResolver
type AnyResolvers = {
[prop in PropertyKey]: (params: any) => any
}
type Resolved<R extends AnyResolvers> = {
[prop in keyof R]: Awaited<ReturnType<R[prop]>>
}
type UnionToIntersection<U> = (U extends any ? (a: U) => any : never) extends ((b: infer A) => any) ? A : never;
const startsWith = (letter: string) =>
(word: string) =>
word[0] === letter;
const isAny = () =>
true;
const lastLetterOf = (word: string): string =>
word[word.length - 1];
const isThenable = value => typeof value?.then === "function";
const wrapHandler = (handler, resolve, reject) => resultOrError => {
try {
const handledResult = handler(resultOrError);
if (isThenable(handledResult)) {
handledResult.then(resolve, reject);
} else {
resolve(handledResult);
@DScheglov
DScheglov / CodingService.java
Last active January 20, 2021 08:05
factory-method
public abstract class CodingService {
abstract Developer createDeveloper();
public void writeCode() {
Developer dev = createDeveloper();
String code = dev.writeCode();
System.out.println(code);
}
}
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { flatMap } from 'rxjs/operators';
import { fromFunctionCall } from '../common/utils';
@Injectable()
export class LoginInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const req = context.switchToHttp().getRequest();
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, Observer } from 'rxjs';
import { flatMap } from 'rxjs/operators';
const nextAndComplete = <T>(observer: Observer<T>, value?: T): void => {
observer.next(result);
observer.complete();
};
@Injectable()