Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
crazy4groovy / lazySelectionSort.js
Last active September 27, 2023 22:30
sort large arrays using the event loop (JavaScript)
View lazySelectionSort.js
function chunkedSelectionSort(arr, callback) {
let i = 0;
function sortStep() {
let lowestIdx = i;
// Find lowest index
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[lowestIdx]) {
lowestIdx = j;
View stateGenerator.js
// Create store accepts reducers map and initial state
function* createStore(reducers, initialState = {}) {
// Initialize state
let state = initialState;
// Extract the reducer keys upfront
const reducerKeys = Object.keys(reducers);
// Combine all reducers into one reducing function
const combinedReducer = (state, action) => {
return reducerKeys.reduce((newState, key) => {
// Pass slice of state into corresponding reducer
@crazy4groovy
crazy4groovy / cacher.ts
Created September 19, 2023 18:06
simple TTL cache, and cache repo (JavaScript, Typescript)
View cacher.ts
export function cacher<T>(thunk: () => Promise<T>, ttlSeconds = 60) {
const noCache: unique symbol = Symbol("cache");
let cache: Promise<T> | symbol = noCache;
return function execThunk(): Promise<T> {
if (typeof cache !== "symbol") {
return cache;
}
cache = thunk();
@crazy4groovy
crazy4groovy / MyPlotFigureChart.jsx
Last active June 20, 2023 15:44
A simple wrapper for Observable Plot charting lib (ReactJS)
View MyPlotFigureChart.jsx
import * as Plot from "@observablehq/plot";
import PlotFigureChart from "./PlotFigureChart.tsx"
export default function MyPlotFigureChart(
{ filteredRequests }: { filteredRequests: Readonly<any[]> }
) {
return (
<PlotFigureChart
options={{
inset: 10,
@crazy4groovy
crazy4groovy / useEventBus.jsx
Last active September 19, 2023 18:06
A simple hook that implements an event bus with useReducer (ReactJS)
View useEventBus.jsx
import React, {
createContext,
useContext,
useEffect,
useRef,
} from "react"
// Create the event bus context
const EventBusContext = createContext({})
// Custom hook to access the event bus context
@crazy4groovy
crazy4groovy / useCustomPollingExample.js
Last active June 12, 2023 18:45
A simple hook to implement interval polling of any thunk (ReactJS)
View useCustomPollingExample.js
import React, { useState } from 'react';
import usePolling from './usePolling';
import ...
const useCustomPolling = () => {
const [state, setState] = useState()
const cb = async (cancelPolling) => {
// do some logics here... whatever...
@crazy4groovy
crazy4groovy / useFetch.js
Last active June 12, 2023 18:46
A simple hook to implement state and data handling of a typical fetch HTTP request (ReactJS)
View useFetch.js
import { useReducer, useRef } from "react";
const initialState = {
isLoading: false,
prevData: undefined,
data: undefined,
error: undefined,
};
const reducer = (state, action) => {
@crazy4groovy
crazy4groovy / ReactForm.jsx
Last active June 12, 2023 18:45
A simple hook to implement form validation (ReactJS)
View ReactForm.jsx
import React from 'react';
import useFormValidation from './useFormValidation';
const initialValues = {
name: '',
email: '',
password: '',
};
// You should put this config in a separate file!
@crazy4groovy
crazy4groovy / ComponentReader.svelte
Last active June 15, 2023 22:39
debounced Svelte store (JavaScript)
View ComponentReader.svelte
<script lang="ts">
/// ...
import { customStoreDebouncer /*, storeDebouncer */ } from "./stores/stringStore";
const stringStoreDebounced = customStoreDebouncer(400); // debounced store read
$: {
const text = $stringStoreDebounced; // resolved value, after debounce timeout
/// ...
}
</script>
@crazy4groovy
crazy4groovy / dl.deno.ts
Last active September 19, 2023 18:10
scrape midjourney "recent showcase" images (into folder, per hour) (JavaScript, Deno)
View dl.deno.ts
import { Timeout, TimeoutError } from "https://deno.land/x/timeout/mod.ts"
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
function newThrottler({ isBusy, lock, unlock, waitMs, size }) {
async function throttler(cb, ...args) {
size(1);
await Promise.resolve();
while (!!isBusy()) {
await delay(waitMs()); // waits in event loop queue, until it interrupts for another attempt!