Skip to content

Instantly share code, notes, and snippets.

@Graniron
Graniron / reduce-to-record.ts
Created September 8, 2022 15:41
Reduce array of items into the Record with provided keys
/**
* Reduce array of items into the Record with provided keys
* reduceToRecord('id', 'name', items): [{ id: 'id1', name: 'John', type: 'web' }] => { id1: 'John' }
*/
export const reduceToRecord = <T, U>(keyName: string, valueName: string, items: U[]): Record<string, T> => {
const keyWithNameReducer = (acc: Record<string, T>, item: U) => {
const key = item[keyName];
const value = item[valueName];
return {
const getUniqueId = () => {
return Math.random()
.toString(36)
.replace(/[^a-z]+/g, '')
.substring(0, 5);
};
const randomElement = (arr) => arr[Math.floor(Math.random() * arr.length)];
enum Status {
DONE: 'done',
ERROR: 'error'
}
const a: Partial<Record<Status, string>> = {}
// or
const a: { [K in Status]?: string } = {}
@Graniron
Graniron / touch-action: manipulation
Created July 11, 2021 06:47
make taps 300ms faster with 1 line of CSS. Element doesn't want double-tap to zoom result: browser *immediately* responds to taps instead of waiting 300ms for a "potential" 2nd tap
a, button {
touch-action: manipulation;
}
<!-- Models -->
interface FilterModel {
name: string;
date: [number, number];
}
type PredicamentFn = <T>(item: T, filters: FilterModel) => boolean;
<!-- Matchers -->
const FILTERS_MATCHERS: Record<keyof FilterModel, PredicamentFn> = {
name: (item, filters) => filters.name.includes(item.name),
@Graniron
Graniron / arrays.utils.ts
Created June 3, 2021 13:34
Arrays utils
<!-- Helpers -->
const isFiniteNumber = (n: any): n is number => Number.isFinite(n);
const isString = (s: any): s is string => s === '' || (s && typeof s.valueOf() === 'string');
const matchId = (valueToMatch: string) => (item: { id: string }) => valueToMatch === item.id;
const sortBy = <T>(valueGetterFn: (item: T) => number | string, direction: 'asc' | 'desc') => (itemA: T, itemB: T): number => {
const a = valueGetterFn(itemA);
const b = valueGetterFn(itemB);
@Graniron
Graniron / has-value.validator.ts
Created June 3, 2021 13:22
NG: hasValueValidator
const hasValueValidator = (formGroup: FormGroup) => {
const hasValue = (val: string | string[]) => Array.isArray(val) ? val.length > 0 : !!val;
const formIsFilled = Object.values(formGroup.value).some(hasValue);
return formIsFilled ? null : { empty: true };
}
@Graniron
Graniron / service.ts
Created December 8, 2017 11:01
Angular: create dynamic component from service
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector
) { }
appendComponentToBody(component: any) {
// 1. Create a component reference from the component
const componentRef = this.componentFactoryResolver
.resolveComponentFactory(component)
var copy = JSON.parse(JSON.stringify(tags));