Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
dmorosinotto / AsyncUtil.cs
Last active Dec 7, 2021
AsyncUtils utility to call an async method from a sincronous context IT WORKS!
View AsyncUtil.cs
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Helper class to run async methods within a sync process.
/// ORIGINAL CODE: https://www.ryadel.com/en/asyncutil-c-helper-class-async-method-sync-result-wait/
/// </summary>
public static class AsyncUtil {
private static readonly TaskFactory _taskFactory = new TaskFactory(CancellationToken.None,
TaskCreationOptions.None,
@dmorosinotto
dmorosinotto / multiCombo.directive.js
Last active Dec 3, 2021
AngularJS multi-combo directive working with mouse & keyboard + simple responsive style based on font-size - TRY LIVE SAMPLE: https://stackblitz.com/edit/web-platform-jjfqgs?file=index.html
View multiCombo.directive.js
angular.module("multiCombo",[])
.directive("multiCombo", function () {
return {
restrict: 'E',
scope: {
value: '=', //VALORE MESSO IN BINDING CON LA SELECT USATO PER INIZIALIZZARE/LEGGERE VALORE TORNATO TIPO: T[valProp] | Array<T[valProp]> SE MULTIPLE
onSelect: '&', //EVENTO NOTIFICA VALORE CAMBIATO onSelect="handle(value)" E' AGGANCIATO AL ng-change DEL <select>
list: '=', //ARRAY DEGLI ITEM DA VISUALIZZARE: T[]
//ATTRIBUTI OPZIONALI
multiple: '@', //BOOLENAO PER INDICARE SE SI VUOLE SELEZIONE MULTIPLA O SINGOLA
@dmorosinotto
dmorosinotto / customOperators.ts
Last active Dec 3, 2021
RxJS usefull custom operators: mapFilter + debug (LIVE SAMPLE https://stackblitz.com/edit/rxjs-74qvro?devtoolsheight=60)
View customOperators.ts
import { map, filter, tap } from "rxjs/operators";
import { Observable } from "rxjs";
export function mapFilter<T,R>(fnTrasformSkipUndefined: (value: T)=>R) {
return function(source: Observable<T>): Observable<Exclude<R, undefined>> {
return source.pipe(map(fnTrasformSkipUndefined), filter(value => value !== undefined)) as Observable<Exclude<R,undefined>>;
}
}
//INSPIRED BY @netbasal ARTICLE https://netbasal.com/creating-custom-operators-in-rxjs-32f052d69457
@dmorosinotto
dmorosinotto / SafeGETPathTypes.ts
Last active Oct 13, 2021
TS strict GET with properties path / Tokenize
View SafeGETPathTypes.ts
/**
* 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 Apr 21, 2021
Angular Pipe to transform value or value$ -> debounced (def 150ms) observable USAGE <cmp [prop]= "value | debounce | async"></cmp>
View debounce.pipe.ts
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 Oct 9, 2020
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
View HACK_DataAdapter.ts
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 Sep 20, 2020
RouterHelpers.ts - some utils function to extract information about Angular current route navigation (ActivatedRoute)
View RouterHelpers.ts
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 Sep 12, 2020
Angular Service to get/inject current ActivatedRoute + Params
View CurrRouteService.ts
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
Angular build --prod problem Function call is not supported in decorators...
@dmorosinotto
dmorosinotto / UnionObj.ts
Last active May 28, 2020
Unionize<T> / Objectify<T> - TypeScript utility helpers to map from Object --> KeyValue Par {k: K , v: V} --> Object
View UnionObj.ts
// 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}