Skip to content

Instantly share code, notes, and snippets.

Avatar
🐚

Seb Insua sebinsua

🐚
View GitHub Profile
View generic-maths-in-ts.ts
type CreateArray<V extends number, Arr extends unknown[] = []> =
Arr extends { length: V } ? Arr: CreateArray<V, [...Arr, 1]>;
type Add<A extends number, B extends number> = [...CreateArray<A>, ...CreateArray<B>]['length'];
type V = Add<2, 3>;
type Sub<A extends number, B extends number> = CreateArray<A> extends [...CreateArray<B>, ...infer Els] ? Els['length'] : never;
type V2 = Sub<10, 1>;
@sebinsua
sebinsua / withDeepPropertyAccessLogger.ts
Created Jun 29, 2022
Debugging the properties in an object which are in use
View withDeepPropertyAccessLogger.ts
import DeepProxy from 'proxy-deep';
export function withDeepPropertyAccessEmitter<T extends object>(
object: T,
emit: (info: {
path: (string | symbol)[];
target: T;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any;
}) => void
View rotate.js
function* unroll(matrix) {
const height = matrix.length;
const width = matrix[0].length;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
yield { y, x };
}
}
}
View clojure.core.js
function createGenerator(maybeIterable) {
const isGenerator = (maybeGenerator) =>
"next" in maybeGenerator &&
typeof maybeGenerator["next"] === "function" &&
"throw" in maybeGenerator &&
typeof maybeGenerator["throw"] === "function" &&
"return" in maybeGenerator &&
typeof maybeGenerator["return"] === "function";
function* generatorFrom(maybeIterable) {
View ShoppingCart.js
import {
useCallback,
useEffect,
useMemo,
useReducer,
useRef,
useState
} from "react";
import { createPortal } from "react-dom";
View TicTacToe.js
import { useState } from "react";
import "./styles.css";
function createGrid(n = 3) {
return Array(n)
.fill(() => Array(n).fill(null))
.map((createRow) => createRow());
}
@sebinsua
sebinsua / closestStraightCity.js
Last active Aug 14, 2022
closestStraightCity.js
View closestStraightCity.js
#!/usr/bin/env node
function closestStraightCity(cities, cityXs, cityYs, queries) {
// We don't need to get the closest city to each city in (cities, cityXs, cityYs),
// as we allow the caller to provide specific queries.
//
// Instead, we use the `queries` to generate a list of city indexes.
const cityIndexes = queries.map((query) =>
cities.findIndex((city) => city === query)
);
View memoize-with-lru-cache.js
function defaultCreateKey(args) {
return JSON.stringify(args);
}
class LruCache {
constructor(capacity = Infinity) {
this.capacity = capacity;
this.cache = new Map();
}
View SinglyLinkedList.js
class SinglyLinkedListNode {
constructor(value) {
this.value = value;
this.tail = null;
}
valueOf() {
return this.value;
}
}
View createMultiMap.js
function createMultiMap(items, { getKeys } = {}) {
if (typeof getKeys !== "function") {
throw new Error(
"The `getKeys` function passed into `createMultiMap` must be a function."
);
}
function set(m, keys, value) {
if (keys.length === 0) {
return;