thats banannas

CODE_SNIPPETS

monkey@keyboard:~$ ls snippets/ | wc -l && echo "snippets loaded"

> Found 5 snippets

> All tested on monkey@keyboard

> Use at your own risk. No refunds. No monkeys harmed.

debounce() JAVASCRIPT
#utility #performance #events
Delays invoking a function until after wait ms have elapsed since the last call. Includes a .cancel() method to abort a pending invocation.
/**
 * debounce
 * Delays fn execution until after `wait` ms have elapsed
 * since the last time it was invoked.
 *
 * @param {Function} fn    Function to debounce
 * @param {number}   wait  Delay in milliseconds (default 300)
 * @returns {Function}     Debounced function with .cancel() method
 *
 * Usage:
 *   const onResize = debounce(() => recalcLayout(), 250);
 *   window.addEventListener('resize', onResize);
 *   // Later: onResize.cancel();
 */
function debounce(fn, wait = 300) {
  let timer = null;

  function debounced(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, wait);
  }

  debounced.cancel = () => {
    clearTimeout(timer);
    timer = null;
  };

  return debounced;
}
fetchWithRetry() JAVASCRIPT
#async #network #resilience
Wraps fetch() with automatic exponential back-off retries and a configurable timeout. Throws after all retries are exhausted.
/**
 * fetchWithRetry
 * fetch() with exponential back-off retry and per-request timeout.
 *
 * @param {string} url
 * @param {object} options   Standard fetch options + optional `timeout` (ms)
 * @param {number} retries   Max attempts (default 3)
 * @param {number} backoff   Initial back-off ms — doubles on each retry (default 300)
 *
 * Usage:
 *   const res  = await fetchWithRetry('/api/data', { timeout: 5000 });
 *   const json = await res.json();
 */
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) {
  const { timeout = 8000, ...fetchOptions } = options;

  const controller = new AbortController();
  const timer      = setTimeout(() => controller.abort(), timeout);

  try {
    const res = await fetch(url, { ...fetchOptions, signal: controller.signal });
    clearTimeout(timer);

    if (!res.ok) throw Object.assign(new Error(`HTTP ${res.status}`), { res });
    return res;

  } catch (err) {
    clearTimeout(timer);

    if (retries <= 0 || err.name === 'AbortError') throw err;

    await new Promise(r => setTimeout(r, backoff));
    return fetchWithRetry(url, options, retries - 1, backoff * 2);
  }
}
rate_limit() PHP
#security #api #php8
IP-based rate limiter backed by APCu. Zero dependencies. Fails open when APCu is unavailable so it never blocks legitimate traffic.
<?php

/**
 * rate_limit
 * IP-based rate limiter using APCu shared memory.
 * Fails open (returns true) when APCu is unavailable.
 *
 * @param string $key     Unique action identifier (e.g. 'login', 'api')
 * @param int    $limit   Maximum requests allowed in the window
 * @param int    $window  Sliding window size in seconds
 * @return bool           true = allowed, false = rate limited
 *
 * Usage:
 *   if (!rate_limit('login', limit: 5, window: 60)) {
 *       http_response_code(429);
 *       header('Retry-After: 60');
 *       exit(json_encode(['error' => 'Too many attempts. Slow down, monkey.']));
 *   }
 */
function rate_limit(string $key, int $limit = 60, int $window = 60): bool
{
    if (!function_exists('apcu_fetch')) {
        return true; // fail open — APCu not available
    }

    $ip     = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $bucket = "rl:{$key}:{$ip}";
    $count  = apcu_fetch($bucket, $exists);

    if (!$exists) {
        apcu_store($bucket, 1, $window);
        return true;
    }

    if ($count >= $limit) {
        return false;
    }

    apcu_inc($bucket);
    return true;
}
.btn-neon CSS
#css #ui #animation
Neon glow button driven entirely by a single CSS custom property. Override --glow-color per instance. Accessible — respects prefers-reduced-motion.
/* ── Neon Glow Button ─────────────────────────────────────────
   Control everything via --glow-color.
   Works on <a>, <button>, or any block/inline element.
   ─────────────────────────────────────────────────────────── */

.btn-neon {
  --glow-color: #39ff14;

  display: inline-block;
  padding: 0.6em 1.8em;
  color: var(--glow-color);
  background: transparent;
  border: 2px solid var(--glow-color);
  font-family: monospace;
  font-size: 1rem;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  text-decoration: none;
  cursor: pointer;
  transition: color 0.2s, background 0.2s, box-shadow 0.2s;
}

.btn-neon:hover,
.btn-neon:focus-visible {
  color: #000;
  background: var(--glow-color);
  box-shadow:
    0 0  8px var(--glow-color),
    0 0 20px var(--glow-color),
    0 0 45px var(--glow-color);
  outline: none;
}

/* ── Colour variants ──── */
.btn-neon--red    { --glow-color: #ff003c; }
.btn-neon--blue   { --glow-color: #00f0ff; }
.btn-neon--purple { --glow-color: #ff00ff; }
.btn-neon--amber  { --glow-color: #ffbf00; }

/* ── Accessibility ──────── */
@media (prefers-reduced-motion: reduce) {
  .btn-neon { transition: none; }
}
FileCache PHP
#caching #php8 #performance
Zero-dependency file-based cache with TTL and a remember() helper. Works on any PHP 8.1+ host — no Redis, no Memcached, no fuss.
<?php

/**
 * FileCache
 * Minimal file-based cache with TTL.
 * PHP 8.1+ — zero dependencies.
 */
final class FileCache
{
    public function __construct(
        private readonly string $dir        = '/tmp/fcache',
        private readonly int    $defaultTtl = 3600,
    ) {
        is_dir($this->dir) || mkdir($this->dir, 0755, recursive: true);
    }

    public function get(string $key): mixed
    {
        $file = $this->path($key);
        if (!file_exists($file)) return null;

        ['expires' => $exp, 'data' => $data] = unserialize(file_get_contents($file));

        if ($exp !== 0 && $exp < time()) {
            unlink($file);
            return null;
        }

        return $data;
    }

    public function set(string $key, mixed $value, int $ttl = 0): void
    {
        file_put_contents(
            $this->path($key),
            serialize(['expires' => $ttl ? time() + $ttl : 0, 'data' => $value]),
            LOCK_EX,
        );
    }

    public function delete(string $key): void
    {
        $f = $this->path($key);
        file_exists($f) && unlink($f);
    }

    /**
     * Get a cached value or compute + store it.
     *
     * $users = $cache->remember('users', 300, fn() => $db->fetchAll('SELECT * FROM users'));
     */
    public function remember(string $key, int $ttl, callable $fn): mixed
    {
        $hit = $this->get($key);
        if ($hit !== null) return $hit;

        $value = $fn();
        $this->set($key, $value, $ttl);
        return $value;
    }

    private function path(string $key): string
    {
        return $this->dir . '/' . hash('xxh3', $key) . '.cache';
    }
}

CONTRIBUTE

Got some cursed code to share?

Submit your worst (or best) snippets and join the chaos.