Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
dmorosinotto / suspensify.ts
Created July 21, 2023 16:16
suspensify() - RxJS operator to convert maybeFailingObs$<T> => Obs$ that never fails and emit "state" { pending, finalized, hasValue + value: T, hasError + error:any }
//ORIGINAL CODE https://github.com/jscutlery/devkit/tree/main/packages/operators
import {
MonoTypeOperatorFunction,
Observable,
ObservableNotification,
OperatorFunction,
ReplaySubject,
} from 'rxjs';
import { debounce, map, materialize, scan, startWith } from 'rxjs/operators';
@dmorosinotto
dmorosinotto / has-role.directive.ts
Last active July 27, 2023 09:41
*hasRole="ROLE" Angular structural directive
import { Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef } from "@angular/core";
import { AuthService } from "./auth.service";
import { Subscription, Subject } from "rxjs";
@Directive({
selector: "[hasRole]",
standalone: true
})
export class HasRoleDirective {
constructor(
@dmorosinotto
dmorosinotto / safeCall.ts
Last active March 8, 2023 15:20
safeCall function (like RUST) + generic SafeResult<T> with TypeScript
//ORIGINAL CODE BY https://twitter.com/mattpocockuk/status/1633064377518628866?s=20
/**
* First, create a type helper that represents
* the result that we'll get from our safe function
*/
export type SafeResult<T> =
| {
ok: true;
value: T;
@dmorosinotto
dmorosinotto / fromReadable.ts
Created February 13, 2023 09:30
RxJS - fromReadableStream operator to trasform Readable Stream -> Observable
//ORIGINAL CODE INSPIRED BY Wassim Chegham https://twitter.com/manekinekko/status/1624440889216057347/photo/1
export function fromReadableStream(
stream: ReadableStream,
signal?: AbortSignal,
writableStrategy?: QueuingStrategy,
readableStrategy?: QueuingStrategy
): Observable<string> {
const createTextDecoderStream = ()=> new TextDecoderStream();
const transformer = () => new TransformStream(
{ transform(chunk, controller) { controller.enqueue(chunk); } }
@dmorosinotto
dmorosinotto / typescript.json
Last active January 26, 2023 10:26
Snippet for @input @output as Observable for Angular (VSCode Cmd+P > Snippets: Configure User Snippets)
"@Input Observable for Angular": {
"prefix": "in$",
"description": "Create an Observable @Input",
"body": [
"#${1:prop} = new BehaviorSubject<${2:type}|undefined>(undefined);",
"protected ${1:prop}\\$ = this.#${1:prop}.pipe(filter(p=>p!==undefined));",
"@Input() set ${1:prop}(value: ${2:type}) {",
"\t$0//if (value!==this.${1:prop}) //eventual validation logic",
"\tthis.#${1:prop}.next(value);",
"}",
@dmorosinotto
dmorosinotto / BaseFormCtrl.ts
Last active November 25, 2022 17:41
Base custom FormControl (NG_VALUE_ACCESSOR implementation) compatible with [(two-way)] + [(ngModel)] + ReactiveForms / ngx-formly ^_^
import { ChangeDetectionStrategy, Directive, EventEmitter, Input, OnDestroy, Output } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { Subject } from "rxjs";
@Directive(/*{
selector: "base-formctrl",
standalone: true,
// templateUrl: "./n-date-picker.component.html", //IL TEMPLATE VA SPECIFICATO SULLA @Component OSSIA LA CLASSE EREDITATA
// styleUrls: ["./n-date-picker.component.css"], //GLI STYLE VANNO SPECIFICATI SULLA @Component OSSIA LA CLASSE EREDITATA
// providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: NBaseFormCtrlComponent, multi: true }], //PURTROPPO QUESTO NON FUNZIONA SULLA ABSTRACT DEVO FARE IL PROVIDER NELLA CLASSE EREDITARE
@dmorosinotto
dmorosinotto / Nullable.ts
Last active November 4, 2022 11:22
Nullable types helper (very short ^_^) for TypeScript
export type N<T> = T | null;
export type NU<T> = T extends undefined ? never : T;
export type NN<T> = NonNullable<T>;
//SAMPLE USE CASES
interface TryNull{
nullable: N<number>;
maybe?: string;
flag?: N<boolean>;
@dmorosinotto
dmorosinotto / Unique.ts
Last active November 4, 2022 23:00
Simulate *nominal types* in TypeScript (aka Brand/Mesure/Unit/Unique/Opaque types)
const __base__: unique symbol = Symbol(); //SUPER TRICK TO DEFINE UNIQUE __base__ TO HOLD THE Type BECAUSE infer DON'T WORK IN inferValue
export type Unique<T, U extends symbol> = T & { readonly __unique: U } & { [__base__]: T };
export type inferValue<U> = U extends Unique<infer T, symbol> ? U[typeof __base__] : never;
export function cast<U extends Unique<unknown, symbol>>(value: inferValue<U>): U { return value as U; }
export function val<U extends Unique<unknown, symbol>>(value: U): inferValue<U> { return value as inferValue<U>; }
//SAMPLE USE CASES
declare const sEUR: unique symbol;
@dmorosinotto
dmorosinotto / Mapped.ts
Last active November 14, 2022 14:26
TS Helpers: Mapped to trasform a Type copying only same props and forcing requied/optionals + Keep & Extract from Object only props of a specific Type
//EXPERIMENTS WITH TYPESCRIPT UTILITY TYPES: https://www.typescriptlang.org/docs/handbook/utility-types.html
//AND MAPPED TYPES: https://mariusschulz.com/blog/mapped-types-in-typescript
//READ MORE HERE: https://blog.logrocket.com/mastering-mapped-types-typescript/
type KeepOnlyPropOfT<O, T> = {
[K in keyof O]: O[K] extends T ? K : never
}[keyof O]
type ExtractOnlyT<O, T> = {
[P in KeepOnlyPropOfT<O,T>]: O[P]
@dmorosinotto
dmorosinotto / site.css
Created October 8, 2022 07:56
Minimal CSS
/* Inspired by https://gist.github.com/JoeyBurzynski/617fb6201335779f8424ad9528b72c41 */
html {
max-width: 70ch;
padding: 3em 1em;
margin: auto;
line-height: 1.75;
font-size: 1.25em;
font-family: Verdana Arial Currier sans-serif Monospace;
box-sizing: border-box;
}