Skip to content

Instantly share code, notes, and snippets.

@christianjuth
christianjuth / machine.js
Last active March 18, 2021 18:56
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
@christianjuth
christianjuth / main.js
Created March 24, 2021 21:27
Memo function
function memo(fn) {
const dict = {}
let id
const perform = { calls: 0, memoHits: 0 }
return (...args) => {
perform.calls++
clearTimeout(id)
id = setTimeout(() => {
console.log(`memo hit rate = ${perform.memoHits}/${perform.calls}`)
}, 1000)
@christianjuth
christianjuth / App.tsx
Last active August 6, 2021 19:18
This is my own React state machine inspired by XState
import { createMachine, useStateMachine } from "./stateMachine";
const machine = createMachine({
initial: "saved",
context: {
input: ""
},
states: {
saved: {
edit: "hasChanges"
@christianjuth
christianjuth / hooks.ts
Last active November 16, 2021 04:45
React Hooks
function useMouseSpeed(updateInterval = 500) {
const lastUpdateRef = useRef(Date.now())
const prevPositionRef = useRef<MousePosition | null> (null)
const currentPositionRef = useRef<MousePosition | null> (null)
const [speed, setSpeed] = useState(0)
useEffect(() => {
function trackMouse({ pageX: x, pageY: y }: MouseEvent) {
x = x / window.innerWidth
y = y / window.innerHeight
@christianjuth
christianjuth / index.ts
Last active February 5, 2022 01:50
Share logic
function openPopup(url: string, height: number, width: number) {
if (typeof window !== "undefined") {
const newwindow = window.open(
url,
"Share Window",
`height=${height}, width=${width}, top=` +
(window.innerHeight / 2 - height) +
", left=" +
(window.innerWidth / 2 - width) +
", toolbar=0, location=0, menubar=0, directories=0, scrollbars=0"