Skip to content

Instantly share code, notes, and snippets.

@araqnid
araqnid / NullableFields.ts
Created February 1, 2023 10:25
Convert optional fields of a Typescript interface to nullable
type NullableFields<T> = Required<{
[K in keyof T]: {} extends Pick<T, K> ? Exclude<T[K], undefined> | null : T[K]
}>
interface Person {
name: string
age?: number
}
const person: NullableFields<Person> = {
@araqnid
araqnid / useSharedObject.tsx
Created January 30, 2023 19:32
Store a shared object in context and copy it to state only where subscribed
import React, { ReactNode, useCallback, useContext, useEffect, useRef, useState } from 'react'
import { BehaviorSubject } from 'rxjs'
type SharedObjectContext<T> = React.Context<BehaviorSubject<T>>
type Transform<T> = (oldValue: T) => T
export function createSharedObjectContext<T>(defaultValue: T): SharedObjectContext<T> {
return React.createContext(new BehaviorSubject<T>(defaultValue))
}
@araqnid
araqnid / UndiciHandler.ts
Last active September 3, 2022 16:08
Undici request handler for aws-sdk
import {HttpHandler, HttpRequest, HttpResponse} from "@aws-sdk/protocol-http";
import {HttpHandlerOptions, RequestHandlerMetadata, RequestHandlerOutput} from "@aws-sdk/types";
import {Agent, Dispatcher} from "undici";
export class UndiciHandler implements HttpHandler {
private readonly agent = new Agent()
metadata: RequestHandlerMetadata = {
handlerProtocol: "http"
}
@araqnid
araqnid / Matcher.kt
Created February 6, 2021 23:41
Match sequence/Flow using a coroutine
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.RestrictsSuspension
import kotlin.coroutines.resume
import kotlin.coroutines.startCoroutine
import kotlin.coroutines.suspendCoroutine
@araqnid
araqnid / DigestTest.kt
Created May 5, 2020 15:35
using messagedigest from Kotlin
import java.security.MessageDigest
import kotlin.test.Test
import kotlin.test.assertTrue
class Scratchpad {
@Test
fun scratchpad() {
val digest = MessageDigest.getInstance("SHA-256")
digest.update("foo".toByteArray())
digest.update("bar".toByteArray())
@araqnid
araqnid / pg_hot_example.sql
Last active February 16, 2021 10:29
example script demonstrating heap-only tuples on postgresql; you need the pageinspect extension installed
create temp table t1(t1_id serial primary key, reference varchar(16) not null unique, value varchar(16) not null);
copy t1(reference, value) from stdin;
FOO foo
BAR bar
QUUX quux
\.
create temp view t1_combined as
select t1_id, reference, value, ctid, lp_flags, lp_off, case when t_ctid <> ctid then t_ctid end as t_ctid,
t_xmin, xmin_visible, case when t_xmax::text <> '0' then t_xmax end as t_xmax, xmax_visible,