Skip to content

Instantly share code, notes, and snippets.

export const isObject = (val: unknown): boolean =>
val instanceof Object && !Array.isArray(val);
export const propertiesToArray = (obj: object): string[] => {
const addDelimiter = (a: string, b: string) => (a ? `${a}.${b}` : b);
const paths = (obj: Record<string, any> = {}, head = ''): string[] => {
return Object.entries(obj).reduce<string[]>((product, [key, value]) => {
const fullPath = addDelimiter(head, key);
return isObject(value)
@arimariojesus
arimariojesus / getDeepValue.ts
Last active October 9, 2022 23:16
Get a deep property of an object. Receive a path in the form of a dot-separated string which sould ignore any value that is not a valid property in the object tree.
export const getDeepValue = <
T extends Record<string, any>,
K extends string = string,
>(
obj: T,
path: DeepKey<T, K> | DeepKey<T, K>[],
): DeepReturn<T, K> => {
const paths = Array.isArray(path) ? path : path.split('.');
return paths.reduce<DeepReturn<T, K>>((acc, curr) => {
return acc[curr];
type DeepReturn<T, K extends string = string> = K extends keyof T
? T[K]
: K extends `${infer TKey}.${infer Rest}`
? TKey extends keyof T
? DeepReturn<Exclude<T[TKey], undefined>, Rest>
: undefined
: undefined;
type ValidValues = string | number | Record<string, any> | Array<any> | undefined | null;
type DeepKey<T extends Record<string, any>, K extends string = string> = K extends keyof T
? T[K] extends ValidValues
? K
: never
: K extends `${infer TKey}.${infer Rest}`
? T[TKey] extends ValidValues
? DeepKey<Exclude<T[TKey], undefined>, Rest> extends never
? never
@arimariojesus
arimariojesus / decodeResponse.js
Last active January 25, 2024 12:15
Decode a xml fetch response with ISO-8859-1 codification to UTF-8
const decodedResponse = await fetch('https://www.anysite.rss.xml', {
headers: {
'Content-Type': 'text/xml;charset=ISO-8859-1',
},
})
.then(r => r.arrayBuffer()) // resolve the response stream for buffer
.then(d => {
const dataView = new DataView(d); // creates a DataView object representing the buffer data
const isoDecoder = new TextDecoder('ISO-8859-1'); // creates an instance of the our decoder
const decodedString = isoDecoder.decode(dataView); // so we pass the stream of bytes for the decoder do its job
@arimariojesus
arimariojesus / customHooks.jsx
Last active April 8, 2021 02:58
setInterval declarative - custom hook
import { useEffect, useRef, useState } from 'react';
const useMyHook = (cb, delay = 1000) => {
const savedCb = useRef();
useEffect(() => {
savedCb.current = cb;
}, [cb]);
useEffect(() => {
@arimariojesus
arimariojesus / ValidateCPF.js
Last active May 3, 2021 22:31
Objeto para validação de CPF
class CPF {
static #filter(cpfRaw) {
if(typeof cpfRaw !== 'string') return;
return cpfRaw.replace(/\D+/g, '');
}
static #isSequence(value) {
const sequence = value[0].repeat(value.length);
return sequence === value;
}