Skip to content

Instantly share code, notes, and snippets.

View andremichelle's full-sized avatar
❤️‍🔥

André Michelle andremichelle

❤️‍🔥
View GitHub Profile
@andremichelle
andremichelle / text-truncate.ts
Last active March 21, 2024 06:07
Truncates the incoming text untill it fits into maxWidth
// Truncates the incoming text untill it fits into maxWidth
// Based on binary-search, hence only log(N) iterations
//
const findMaxFittingText = (context: CanvasRenderingContext2D, text: string, maxWidth: number): string => {
let l: number = 0
let r: number = text.length
while (l < r) {
const mid: number = (r + l) >> 1
const testString = text.substring(0, mid + 1)
if (Math.ceil(context.measureText(testString).width) <= maxWidth) {
@andremichelle
andremichelle / weak.ts
Created December 20, 2023 10:48
WeakRefSet holds weak references and is iterable
export class WeakRefSet<T extends WeakKey> {
readonly #set = new Set<WeakRef<T>>()
add(value: T): void {this.#set.add(new WeakRef<T>(value))}
forEach(callback: (value: T) => void): void {
for (const weakRef of this.#set) {
const value = weakRef.deref()
if (value === undefined) {
this.#set.delete(weakRef)
@andremichelle
andremichelle / video.ts
Last active November 10, 2023 04:30
This code enables efficient looping of WebM videos by streaming and caching them in memory. It prevents the browser from repeatedly streaming the video when the loop property triggers a restart, ensuring a smooth and resource-friendly playback experience.
// Tested on all major browsers (Macbook Pro), Fails on IOS (https://caniuse.com/?search=MediaSource)
export const streamAndCacheMediaSource = (videoElement: HTMLVideoElement, url: string): void => {
const MimeCodec = "video/webm; codecs=\"vp9\""
if (!MediaSource.isTypeSupported(MimeCodec)) {throw new Error(`${MimeCodec} is not supported`)}
const mediaSource = new MediaSource()
mediaSource.addEventListener("sourceopen", async () => {
if (mediaSource.readyState !== "open") {throw new Error("readyState not open")}
const sourceBuffer = mediaSource.addSourceBuffer(MimeCodec)
sourceBuffer.mode = "sequence"
sourceBuffer.addEventListener("error", () => {throw new Error("Unknown error. Check 'chrome://media-internals/'")})
@andremichelle
andremichelle / callIfExists.ts
Last active October 28, 2022 14:13
Safe call to optional methods in interface (nice for visitor pattern)
class Bar { type: 'bar' = 'bar' }
interface Foo {
hello?(): string
world?(event: Bar, foo: number): string
george?(): string
}
const bar: Foo = {
hello: () => 'world',
@andremichelle
andremichelle / shadertoy.kt
Created June 26, 2020 04:26
One file shadertoy shaders to openrndr
import org.openrndr.application
import org.openrndr.draw.*
import org.openrndr.internal.Driver
import org.openrndr.math.Vector2
import org.openrndr.math.Vector3
import java.io.File
class ShaderToy(fsCode: String) {
companion object {
fun fromFile(pathname: String): ShaderToy {