Skip to content

Instantly share code, notes, and snippets.

@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;
}
@dmorosinotto
dmorosinotto / download_CSV.ts
Created June 28, 2022 14:12
Export to CSV + File download via JS
public csvData<T>(arr: T[], keys: Array<{ field: string, title?: string}> = []): string {
//MD EXPORT
//CONVERTE ARRAY DATI -> CSV CON PRIMA RIGA NOME CAMPI
const sep = ";";
if (arr && arr.length) {
if (keys == null || keys.length == 0) keys = Object.keys(arr[0]).map(k => ({ field: k, title: k }));
const titles = keys.map(key => key.title || key.field);
let csv = arr.map(obj => {
let row: string[] = [];
keys.forEach(key => {
@dmorosinotto
dmorosinotto / ApiClient.ts
Last active February 8, 2022 10:52
ApiClient class using fetch + retry backoff logic
//ORIGINAL CODE BY @BenNadel READ ARTICLE: https://www.bennadel.com/blog/4200-using-fetch-abortsignal-and-settimeout-to-apply-retry-mechanics-in-javascript.htm
// Regular expression patterns for testing content-type response headers.
const RE_CONTENT_TYPE_JSON = new RegExp("^application/(x-)?json", "i");
const RE_CONTENT_TYPE_TEXT = new RegExp("^text/", "i");
// Static strings.
const UNEXPECTED_ERROR_MESSAGE = "An unexpected error occurred while processing your request.";
type TKeyValue<T> = Record<string, T>;
type TMethods = "GET" | "get" | "POST" | "post" | "PUT" | "put" | "DELETE" | "delete";
@dmorosinotto
dmorosinotto / launch.json
Created February 3, 2022 17:58
VSCode launch.json - to Debug with Edge
{
"version": "0.2.0",
"configurations": [{
"type": "pwa-msedge",
"request": "launch",
"name": "webdebug",
"url": "http://localhost:4200",
"webRoot": "${workspaceFolder}",
"runtimeExecutable": "stable",
"runtimeArgs": ["--headless"]
@dmorosinotto
dmorosinotto / AsyncUtil.cs
Last active September 10, 2023 15:27
C# AsyncUtils utility to call an async method from a sincronous context IT WORKS!
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 December 3, 2021 11:57
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
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 December 3, 2021 11:30
RxJS usefull custom operators: mapFilter + debug (LIVE SAMPLE https://stackblitz.com/edit/rxjs-74qvro?devtoolsheight=60)
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