Skip to content

Instantly share code, notes, and snippets.

@tlux
tlux / EnumTypeConverter.kt
Last active September 15, 2024 01:17
Hibernate Attibute Converter for Enums
abstract class EnumConverter<T : Enum<T>, V>(
private val entries: EnumEntries<T>,
private val dumpValue: (T) -> V
) : AttributeConverter<T, V> {
override fun convertToDatabaseColumn(enumValue: T?): V? {
return enumValue?.let { dumpValue(it) }
}
override fun convertToEntityAttribute(dbValue: V?): T? {
return dbValue?.let { value ->
@tlux
tlux / Duplicates.kt
Last active September 2, 2024 18:13
Kotlin extensions to find duplicates in an Iterable
/**
* Gets a set of duplicates in the given iterable.
*/
fun <T> Iterable<T>.duplicates(): Set<T> = duplicatesBy { it }
/**
* Gets a set of duplicates in the given iterable using the specified selector.
*/
fun <T, K> Iterable<T>.duplicatesBy(selector: (T) -> K): Set<K> =
groupingBy(selector).eachCount().filterValues { it > 1 }.keys.toSet()
@tlux
tlux / observable.ex
Last active August 14, 2024 17:55
Simple Elixir Observable using GenStage
defmodule Observable do
@moduledoc """
A module that provides creating an observible value that emits the values to
a stream.
"""
alias Observable.Server
defstruct [:producer, :consumer]
@tlux
tlux / FlowDedup.kt
Last active July 31, 2024 22:57
Kotlin Flow Dedup Extension Functions
import kotlinx.coroutines.flow.flow
inline fun <T> Flow<T>.dedupBy(crossinline predicate: suspend (T, T) -> Boolean): Flow<T> =
let { source ->
var prevValue: T? = null
flow {
source.collect { value ->
if (prevValue == null || !predicate(prevValue!!, value)) {
prevValue = value
emit(value)
@tlux
tlux / FieldsOfType.ts
Last active October 3, 2023 15:27
Extract fields of a specific type from a Record in TypeScript
type AllowedFieldsWithType<TObj, TKey> = {
[K in keyof TObj]: TObj[K] extends TKey ? K : never;
};
export type FieldsOfType<T, K> = AllowedFieldsWithType<T, K>[keyof T];
// Usage Example:
//
// const obj = {
// foo: 'bar',
@tlux
tlux / cloneDeep.ts
Last active October 13, 2023 11:47
Some Typescript utility functions for the real world
/**
* Creates a deep clone of an object.
*
* Internally uses `structuredClone` when available and
* `JSON.parse(JSON.stringify(obj))` as fallback.
*
* @param obj - The object to be cloned.
* @return The deep clone of the object.
*/
export default function cloneDeep<T>(value: T): T {
@tlux
tlux / useScroll.ts
Last active March 24, 2023 03:22
React hook to track and set scroll position of an element
import { RefObject, useCallback, useEffect, useState } from 'react';
export interface ScrollToOptions {
x?: number;
y?: number;
behavior?: ScrollBehavior;
}
export interface UseScrollOptions {
disabled?: boolean;
@tlux
tlux / context.ts
Created March 15, 2023 12:59
Simple TypeScript wrapper to set and get Svelte contexts
import { getContext, setContext } from "svelte";
/**
* The context object.
*/
export interface Context<T> {
get: () => T;
set: (ctx: T) => T;
}
@tlux
tlux / findValue.test.ts
Last active March 2, 2023 09:41
TypeScript helper to find a value in an array, inspired by Elixir's Enum.find_value
import findValue, { FindValueFilterMapper } from './findValue';
describe('findValue(value, predicate)', () => {
const FILTER_MAPPER: FindValueFilterMapper<number, string> = (v) => {
if (v < 0) {
return [true, 'negative'];
}
if (v % 2 === 1) {
return [false, 'odd'];
}
@tlux
tlux / eventually.js
Last active March 1, 2022 14:09
A simple function that resolves when a call eventually does not fail or rejects after a timeout - nice for tests performing async work
export default function eventually(callback, timeout = 2000, pollInterval = 50) {
return new Promise((resolve, reject) => {
let intervalTimer;
let lastError;
const timeoutTimer = setTimeout(() => {
if (!intervalTimer) return;
clearTimeout(intervalTimer);
reject(lastError || new Error('eventually timed out'));