Skip to content

Instantly share code, notes, and snippets.

@dkacper
dkacper / Publisher.ts
Created April 26, 2024 13:15
Publish-subscriber. Implementation of observer pattern in TypeScript.
type Subscriber<TData> = (data: TData) => void;
interface IPublisher<TEvent, TData> {
subscribe(event?: TEvent): (subscriber: Subscriber<TData>) => () => void;
notify(event: TEvent, data: TData): void;
}
export class Publisher<TEvent, TData> implements IPublisher<TEvent, TData> {
protected subscribers: { event: TEvent; subscriber: Subscriber<TData> }[] = [];
@dkacper
dkacper / abstract-mapper.ts
Created August 10, 2022 09:39
Abstract Mapper
export abstract class Mapper<TDomain, TDto = unknown> {
// public static map: Mapper<TDomain, TDto>; Add this property to a mapper to access methods like they were static.
public abstract toDto?: (domain: TDomain) => TDto;
public abstract toDomain?: (dto: TDto) => TDomain;
}
@dkacper
dkacper / nbspScript.ts
Created June 4, 2022 13:29
A pure function that adds nbsp between one-character word and a previous word.
export const nbspScript = (text: string) => {
const input = text.split(' ');
let output = input[input.length - 1];
for (let index = 0; index < input.length; index++) {
const reversedIndex = input.length - index - 1;
const word = input[reversedIndex];
if (reversedIndex !== input.length - 1) {
if (word.length > 1) {
output = `${word} ${output}`;
} else {
@dkacper
dkacper / useContextSafe.ts
Last active May 5, 2022 08:29
React useContext hook but with a safe type check that makes sure context is not undefined.
import { Context, useContext } from 'react';
export const useContextSafe = <TContext>(
context: Context<TContext>
): NonNullable<TContext> => {
const ctxValue = useContext(context);
if (!ctxValue) {
throw new Error(
`Cannot read ${context.displayName} context. You may have forgot to wrap it with the Provider`
);