Skip to content

Instantly share code, notes, and snippets.

@gchumillas
gchumillas / 1. use-breakpoints.ts
Last active March 17, 2024 13:41
breakpoints hook
import { useCallback, useMemo, useEffect } from 'react'
export const useBreakpoints = <T extends Record<string, number>>(breakpoints: T): keyof T | undefined => {
const searchBreakpoint = useCallback((breakpoints: { key: string, value: number }[]) => {
return breakpoints.find((x) => window.innerWidth < x.value)?.key
}, [])
const entries = useMemo(() => {
return Object
.entries(breakpoints)
@gchumillas
gchumillas / 1. use-validator.ts
Last active May 23, 2024 18:29
validate forms hook
import { useCallback, useMemo, useState } from 'react';
const useValidator = <T extends Record<string, string>>(validator: () => T) => {
const [errors, setErrors] = useState<Partial<T>>({})
return useMemo(() => ({
validate: () => {
setErrors(validator())
return Object.values(errors).every((x) => !x)
},
extension Array where Element: Collection {
// Calculates the size of a matrix.
func size() -> (cols: Int, rows: Int) {
let numRows = self.count
let numCols = self.reduce(0, { Swift.max($0, $1.count) })
return (numCols, numRows)
}
// Transposes a matrix.
//
extension String {
func leftTrimmed() -> Self {
guard let i = self.firstIndex(where: { !$0.isWhitespace }) else {
return ""
}
return "\(self[i...])"
}
func rightTrimmed() -> Self {
guard let i = self.lastIndex(where: { !$0.isWhitespace }) else {
extension String {
func chunks(_ size: Int) -> [String] {
stride(from: 0, to: self.count, by: size).map {
let i0 = self.index(self.startIndex, offsetBy: $0)
let i1 = self.index(self.startIndex, offsetBy: min($0 + size, self.count))
return "\(self[i0..<i1])"
}
}
}
@gchumillas
gchumillas / code-generator.ts
Last active October 5, 2021 06:29
Code generator
import { Db } from 'mongodb'
// Increments the `count` field of the `codes` collection and returns it.
// This function is "thread safety".
//
// It's important to update and find the document at the same time.
// Otherwise a "race condition" may arise.
const newCode = async (db: Db, name: string) => {
const { value: { count } } = await db.collection('codes').findOneAndUpdate({ name }, { $inc: { count: 1 } }, {
upsert: true,
@gchumillas
gchumillas / sort.ts
Last active September 7, 2021 17:36
Sort a list of objects by fields
/**
* Sorts a list list of records by fields.
*
*
* Example 1:
*
* const items = [
* { currency: 'EUR', amount: 101.45 },
* { currency: 'EUR', amount: 33.23 },
* { currency: 'EUR', amount: 55.00 },
@gchumillas
gchumillas / pick.ts
Created September 6, 2021 16:59
Pick a random item from a list
/**
* Picks a random item from a list.
*
* For example:
*
* pick(['a', 'b', 'c'], [0.7, 0.2])
* // outputs 'a' with 70% chance
* // outputs 'b' with 20% chance
* // outputs 'c' with 10% chance (the rest)
*
import React from 'react'
import _ from 'lodash'
export type Validator = (val: any) => string | true
const useValidator = ({
defaultValidator = () => true,
validators
}: {
defaultValidator?: Validator