Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
dmorosinotto / SafeGETPathTypes.ts
Last active October 13, 2021 14:01
TS strict GET with properties path / Tokenize
/**
* EnhanceTokenizedArray to resolve problem with Index array in path string.
* type Test = EnhanceTokenizedArray<Tokenize<'foo.0.bar', '.'>>; // Returns ['foo', number, 'bar']
*/
type StringLookingLikeANumber = `${number}`;
type EnhanceTokenizedArray<S> =
S extends [infer Head, ...infer Rest] ?
Head extends StringLookingLikeANumber ? [number, ...EnhanceTokenizedArray<Rest>]
: [Head, ...EnhanceTokenizedArray<Rest>]
: [];
@dmorosinotto
dmorosinotto / debounce.pipe.ts
Created April 21, 2021 08:43
Angular Pipe to transform value or value$ -> debounced (def 150ms) observable USAGE <cmp [prop]= "value | debounce | async"></cmp>
import { OnDestroy, Pipe, PipeTransform } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Pipe({ name: 'debounce', pure: true })
export class DebouncePipe implements PipeTransform, OnDestroy {
private _bs: BehaviorSubject<any>;
private _obs: Observable<any>;
private _old: any;
@dmorosinotto
dmorosinotto / HACK_DataAdapter.ts
Last active October 9, 2020 07:46
HACK Angular Material DataAdapter to use DATE @t12:00:00Z UTC so it'll be always in the SAME DAY regardless of the Browser Timezone/Locale
import { Injectable } from "@angular/core"
import { MatNativeDateModule, MAT_DATE_FORMATS, MatDateFormats, MAT_DATE_LOCALE, DateAdapter, NativeDateAdapter } from "@angular/material/core";
@Injectable()
//@ts-ignore
export class MY_FIX_DATAADAPTER extends NativeDateAdapter {
private _createDateWithOverflow(year: number, month: number, date: number) {
// HACK: REPLACE ANGULAR private IMPLEMENTATION SETTING DATE WITH T12:00:00Z UTC !!!
// SO REGADLESS OF THE CLIENT BROWSER TIMEZONE IT'LL ALWAYS BE IN THE SAME DAY EVEN THE LOCALDATE!!!
const d = new Date();
@dmorosinotto
dmorosinotto / RouterHelpers.ts
Last active September 20, 2020 14:24
RouterHelpers.ts - some utils function to extract information about Angular current route navigation (ActivatedRoute)
import { ActivatedRoute, ActivatedRouteSnapshot, ParamMap} from "@angular/router";
//SERIALIZE paramMap -> string THIS UTILS SORT KEYS TO ENSURE THAT THE OUTPUT string WILL BE COMPARABLE EVEN IF par ORDER CHANGE
//A SIMPLIFIED VERSION CAN return JSON.stringify(params) BUT THE SERIALIZE ORDER OF KEYS -> JSON IS NOT PREDICTABLE / COMPARABLE
export function paramMapToString(params: ParamMap, sep: string="\n"): string {
if (!params) return "";
const sortedKeys = params.keys.sort();
return sortedKeys.map( key => {
let val = params.getAll(key);
if (!val || !val.length) return "";
@dmorosinotto
dmorosinotto / CurrRouteService.ts
Created September 12, 2020 10:06
Angular Service to get/inject current ActivatedRoute + Params
import {Injectable} from "@angular/core";
import {ActivatedRoute, NavigationEnd, Router} from "@angular/router";
import {Observable} from "rxjs";
import {first, filter, map, switchMap} from "rxjs/operators";
@Injectable({providedIn: 'root'})
export class CurrRouteService {
constructor(
private route: ActivatedRoute,
private router: Router
@dmorosinotto
dmorosinotto / READ.md
Created May 29, 2020 16:53
Angular build --prod problem Function call is not supported in decorators...
@dmorosinotto
dmorosinotto / UnionObj.ts
Last active May 28, 2020 07:00
Unionize<T> / Objectify<T> - TypeScript utility helpers to map from Object --> KeyValue Par {k: K , v: V} --> Object
// Utility types to map from Object --(Unionize)--> KeyValue Pair {k: K, v: V} --(Objectify)--> back to Object
// helpful in case where you need to "tasform/filter/extract" some prop in the Object using Conditional Types
// ORIGINAL CODE + READ MORE INFO/SAMPLE USE CASES: https://effectivetypescript.com/2020/05/12/unionize-objectify/
type Unionize<T extends object> = {
[k in keyof T]: {k: k; v: T[k]}
}[keyof T];
// type PropertyKey = keyof any = string | number | symbol
type KVPair = {k: PropertyKey; v: unknown}
@dmorosinotto
dmorosinotto / updateValidity.ts
Created May 10, 2020 06:28
updateValidity for AbstractControl (set/force locally + correctly propagate after if status changed)
export function updateValidity(c: AbstractControl) {
const status = c.status;
c.updateValueAndValidity({ emitEvent: false });
if (status !== c.status) {
(c.statusChanges as EventEmitter<string>).emit(c.status);
}
}
@dmorosinotto
dmorosinotto / base.component.ts
Last active November 6, 2024 23:26
Angular BaseComponent with handle destroy$ and takeUntil pattern to unsubscribe!
import { Directive, OnDestroy } from "@angular/core";
import { Subject } from "rxjs";
import { takeUntil } from "rxjs/operators";
@Directive() // Needed only for Angular v9+ strict mode that enforce decorator to enable Component inheritance
export abstract class BaseComponent implements OnDestroy {
// _destroy$ is LAZY: it'll be created (and allocate memory) only if you use takeUntilDestroy
private _destroy$?: Subject<void>;
protected takeUntilDestroy = <T>() => {
if (!this._destroy$) this._destroy$ = new Subject<void>(); // LAZY Subject
@dmorosinotto
dmorosinotto / GenericHandler.cs
Created January 11, 2020 08:18
C# generic handler discovery and registration/dispatch
// types
public interface IHandleForwarder
{
object ForwardToHandle(object input);
}
public abstract class AbstractMessageHandler<TIn,TOut> : IHandleForwarder
{
public abstract TOut Handle(TIn input);