Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
dmorosinotto / toDictionary.ts
Last active November 16, 2023 13:14
Generic indexBy function + toDictionary RxJS Operator
import { type Observable } from 'rxjs';
import { map } from "rxjs/operators";
//GENERIC toDictionary OPERATOR + indexBy FUNCTION RETURN Map<indexOf, item> TO OTTIMIZE O(1) EXIST/RETRIVE OF ITEM BY idxOf (.has(idx)/.get(idx))
export type Indexer<T extends {}> = keyof T | ((item: T) => unknown);
export type IndexOf<T, I extends Indexer<T>> = I extends keyof T ? T[I] : I extends (...args: any) => any ? ReturnType<I> : never;
export const indexBy = <T, I extends Indexer<T>>(array: T[], keyOrIndexer: I): Map<IndexOf<T, I>, T> => {
if (!array) return new Map<IndexOf<T, I>, T>();
const idexerFn: (item: T) => IndexOf<T, I> = (
typeof keyOrIndexer === "function" ? keyOrIndexer : (item: T) => item[keyOrIndexer as keyof T]
@dmorosinotto
dmorosinotto / provideControlContainer.ts
Created October 6, 2023 12:05
Helper to "compose" Reactive forms from different component -> use viewProviders: [provideControlContainer()],
//ORIGINAL CODE BY Nevzat Topçu @nevzatopcu
//STACKBLIZ SAMPLE https://stackblitz.com/edit/angular-form-share-elements?file=src%2Fmain.ts
//READ MORE HERE: https://nevzatopcu.medium.com/angular-child-components-with-reactive-forms-fbf4563b304c
import { Optional, SkipSelf, Provider } from '@angular/core';
import { ControlContainer } from '@angular/forms';
const containerFactory = (container: ControlContainer): ControlContainer => {
if (!container) {
throw new Error('I need a FormGroup instance');
@dmorosinotto
dmorosinotto / my-utils.ts
Last active September 2, 2023 23:38
Some generic Utils: log, after, ...
const LOGTYPES = ['log', 'info', 'warn', 'error'] as const;
interface LogType {
type: typeof LOGTYPES[number];
}
export const log = (...args: Array<string | LogType | {}>) => {
let type: LogType['type'] = 'log';
let prefix = [] as any[];
let postfix = [] as any[];
//@ts-ignore
const idx = args.findIndex((a) => LOGTYPES.includes(a?.type));
@dmorosinotto
dmorosinotto / NConsole.d.ts
Last active August 30, 2023 15:48
Logger client side that override console to send all Errors to backend ( POST base64(JSON) --> /Log/Error )
//CONSOLE LOG OVEERIDE DEFINITION BY LELE 2023-08-30
// declare global {
type NLogLevel = 'log' | 'info' | 'warn' | 'error' | 'none';
interface NLogOptions {
NDebug?: boolean;
NLogLevel?: NLogLevel;
NShowLevel?: NLogLevel;
NAgent?: string;
NApp?: string;
@dmorosinotto
dmorosinotto / MapPath_Extensions.cs
Created August 27, 2023 16:22
MapPath() Extension Method in ASP.NET: Map Physical Paths with an HttpContext.
//ORIGINAL CODE BY RICK STRAHL https://weblog.west-wind.com/posts/2023/Aug/15/Map-Physical-Paths-with-an-HttpContextMapPath-Extension-Method-in-ASPNET
public static class HttpContextExtensions
{
static string WebRootPath { get; set; }
static string ContentRootPath { get; set; }
/// <summary>
/// Maps a virtual or relative path to a physical path in a Web site,
/// using the WebRootPath as the base path (ie. the `wwwroot` folder)
/// </summary>
@dmorosinotto
dmorosinotto / pdfjs-serverless_deno.ts
Created August 27, 2023 16:04
A nodeless/serverless redistribution of Mozilla's PDF.js for serverless enviroments, like Deno Deploy and Cloudflare Workers with zero dependencies.
//ORIGINAL CODE REPO: https://github.com/johannschopplich/pdfjs-serverless
//# pnpm
//pnpm add pdfjs-serverless
//# npm
//npm install pdfjs-serverless
import { getDocument } from 'https://esm.sh/pdfjs-serverless'
const data = Deno.readFileSync('./dummy.pdf')
const doc = await getDocument(data).promise
@dmorosinotto
dmorosinotto / using_bcrypt.js
Created August 27, 2023 15:58
Using BCrypt to hash password in Node.js
//READ MORE IN THIS ARTICLE https://morioh.com/a/782c0022755e/using-bcrypt-to-hash-passwords-in-nodejs EXPECIALLY PRE-REQUISITE
const bcrypt = require("bcrypt")
const saltRounds = 10
const password = "Admin@123"
//Password encryption + explicit Salt
bcrypt
.genSalt(saltRounds)
.then(salt => {
@dmorosinotto
dmorosinotto / Chau_computeFrom.ts
Last active August 21, 2023 06:29
computedFrom - Useful function to combine Signal, Observable, Promise -> toSignal + optional pipe operators chain //INSPIRED BY @Enea_Jahollari ARTICLE https://dev.to/this-is-angular/a-sweet-spot-between-signals-and-observables-4chb
//ORIGINAL CODE BY CHAU: https://gist.github.com/eneajaho/33a30bcf217c28b89c95517c07b94266
import { isSignal, Signal, untracked } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import {
combineLatest,
distinctUntilChanged,
from,
isObservable,
ObservableInput,
of,
@dmorosinotto
dmorosinotto / trackby.directive.ts
Last active September 16, 2023 17:25
TrackById, TrackByProp directives to simplify use of trackBy in Angular *ngFor
//INSPIRED BY https://medium.com/ngconf/make-trackby-easy-to-use-a3dd5f1f733b
import { Directive, inject, Provider } from "@angular/core";
import { ngForOf, NgIterable } from "@angular/common";
@Directive({
selector: "[ngForTrackById]",
standalone: true
})
export class NgForTrackByIdDirective<T extends { id: string | number }> {
@dmorosinotto
dmorosinotto / create-effect.ts
Last active July 31, 2023 13:28 — forked from e-oz/create-effect.ts
Helper function to handle async call and push value to Signal
//Helper function to handle async call (Observable generator with strategy + safe retry if error) to push value to Signal - useful for State Management with Signal
//READ MORE https://medium.com/@eugeniyoz/application-state-management-with-angular-signals-b9c8b3a3afd7
//ORIGINAL DOCS (NgRx component-store effect) https://ngrx.io/guide/component-store/effect#effect-method
import { isObservable, Observable, of, retry, Subject, Subscription } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { DestroyRef, inject } from '@angular/core';
/**
* This code is a copied `ComponentStore.effect()` method from NgRx and edited to:
* 1) be a standalone function;