Build a resizable split-pane layout with drag handle

Solution:
function createSplitPane(containerSelector, options = {}) {
  const container = document.querySelector(containerSelector);
  if (!container) throw new Error('Split pane container not found');

  const { direction = 'horizontal', initialRatio = 0.5, minSize = 100 } = options;
  const isHorizontal = direction === 'horizontal';

  container.style.display = 'flex';
  container.style.flexDirection = isHorizontal ? 'row' : 'column';
  container.style.height = '100%';
  container.style.overflow = 'hidden';

  const pane1 = document.createElement('div');
  pane1.className = 'pane pane-1';
  pane1.style.flex = `0 0 calc(${initialRatio * 100}% - 4px)`;
  pane1.style.overflow = 'auto';
  pane1.style.minWidth = isHorizontal ? minSize + 'px' : 'auto';
  pane1.style.minHeight = !isHorizontal ? minSize + 'px' : 'auto';

  const handle = document.createElement('div');
  handle.className = 'split-handle';
  handle.style.flex = '0 0 8px';
  handle.style.background = '#e0e0e0';
  handle.style.cursor = isHorizontal ? 'col-resize' : 'row-resize';
  handle.style.userSelect = 'none';

  const pane2 = document.createElement('div');
  pane2.className = 'pane pane-2';
  pane2.style.flex = '1 1 auto';
  pane2.style.overflow = 'auto';
  pane2.style.minWidth = isHorizontal ? minSize + 'px' : 'auto';
  pane2.style.minHeight = !isHorizontal ? minSize + 'px' : 'auto';

  container.appendChild(pane1);
  container.appendChild(handle);
  container.appendChild(pane2);

  let isDragging = false;
  const sizeProp = isHorizontal ? 'clientWidth' : 'clientHeight';

  handle.addEventListener('mousedown', (e) => {
    isDragging = true;
    document.body.style.cursor = isHorizontal ? 'col-resize' : 'row-resize';
  });

  document.addEventListener('mousemove', (e) => {
    if (!isDragging) return;
    const rect = container.getBoundingClientRect();
    const pos = isHorizontal ? e.clientX - rect.left : e.clientY - rect.top;
    const ratio = Math.max(minSize, Math.min(pos, rect[sizeProp] - minSize)) / rect[sizeProp];
    pane1.style.flex = `0 0 calc(${ratio * 100}% - 4px)`;
  });

  document.addEventListener('mouseup', () => {
    isDragging = false;
    document.body.style.cursor = '';
  });

  return { pane1, pane2, handle };
}

// Usage: createSplitPane('#editor-layout', { direction: 'horizontal', initialRatio: 0.4 });


Implement a masonry image grid with lazy loading and lightbox

Solution:
function createMasonryGallery(containerSelector, imageUrls) {
  const container = document.querySelector(containerSelector);
  if (!container) throw new Error('Gallery container not found');

  container.style.columnCount = '3';
  container.style.columnGap = '1rem';

  if (!Array.isArray(imageUrls)) throw new TypeError('imageUrls must be an array');

  // Lightbox overlay
  const lightbox = document.createElement('div');
  lightbox.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.9);display:none;align-items:center;justify-content:center;z-index:1000;';
  const img = document.createElement('img');
  img.style.maxWidth = '90vw';
  img.style.maxHeight = '90vh';
  img.style.objectFit = 'contain';
  lightbox.appendChild(img);
  lightbox.addEventListener('click', () => { lightbox.style.display = 'none'; });
  document.body.appendChild(lightbox);

  imageUrls.forEach((src, i) => {
    const wrapper = document.createElement('div');
    wrapper.style.breakInside = 'avoid';
    wrapper.style.marginBottom = '1rem';

    const image = document.createElement('img');
    image.dataset.src = src;
    image.alt = `Gallery image ${i + 1}`;
    image.style.width = '100%';
    image.style.borderRadius = '8px';
    image.style.display = 'block';
    image.style.background = '#a29bfe';
    image.style.minHeight = '150px';

    image.addEventListener('click', () => {
      img.src = src;
      lightbox.style.display = 'flex';
    });

    wrapper.appendChild(image);
    container.appendChild(wrapper);
  });

  // Lazy loading
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting && entry.target.dataset.src) {
        entry.target.src = entry.target.dataset.src;
        delete entry.target.dataset.src;
        observer.unobserve(entry.target);
      }
    });
  }, { rootMargin: '200px' });

  container.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));
  return { container, lightbox, observer };
}

// Usage: createMasonryGallery('#gallery', ['/img/1.jpg', '/img/2.jpg']);


Create an image carousel with touch swipe and keyboard controls

Solution:
function createCarousel(containerSelector, slides) {
  const container = document.querySelector(containerSelector);
  if (!container) throw new Error('Carousel container not found');
  if (!Array.isArray(slides) || slides.length === 0) throw new Error('Slides array required');

  let current = 0;

  container.innerHTML = `

      <button class="prev" style="position:absolute;left:1rem;top:50%;transform:translateY(-50%);" aria-label="Previous slide">←</button>
      <button class="next" style="position:absolute;right:1rem;top:50%;transform:translateY(-50%);" aria-label="Next slide">→</button>

  `;

  const track = container.querySelector('.track');
  const indicators = container.querySelector('.indicators');

  slides.forEach((slide, i) => {
    const div = document.createElement('div');
    div.style.minWidth = '100%';
    div.innerHTML = slide;
    track.appendChild(div);

    const dot = document.createElement('button');
    dot.style.width = '10px';
    dot.style.height = '10px';
    dot.style.borderRadius = '50%';
    dot.style.border = 'none';
    dot.style.background = i === 0 ? '#fff' : 'rgba(255,255,255,0.4)';
    dot.addEventListener('click', () => goTo(i));
    indicators.appendChild(dot);
  });

  function goTo(index) {
    current = ((index % slides.length) + slides.length) % slides.length;
    track.style.transform = `translateX(-${current * 100}%)`;
    Array.from(indicators.children).forEach((dot, i) => {
      dot.style.background = i === current ? '#fff' : 'rgba(255,255,255,0.4)';
    });
  }

  container.querySelector('.prev').addEventListener('click', () => goTo(current - 1));
  container.querySelector('.next').addEventListener('click', () => goTo(current + 1));

  // Touch swipe
  let startX = 0;
  container.addEventListener('touchstart', (e) => { startX = e.touches[0].clientX; });
  container.addEventListener('touchend', (e) => {
    const diff = startX - e.changedTouches[0].clientX;
    if (Math.abs(diff) > 50) goTo(current + (diff > 0 ? 1 : -1));
  });

  // Keyboard
  container.setAttribute('tabindex', '0');
  container.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowLeft') goTo(current - 1);
    if (e.key === 'ArrowRight') goTo(current + 1);
  });

  return { goTo, getCurrent: () => current };
}

// Usage: createCarousel('#carousel', ['', '']);


Build an infinite scroll image feed with skeleton placeholders

Solution:
function createInfiniteFeed(containerSelector, fetchPage, options = {}) {
  const container = document.querySelector(containerSelector);
  if (!container) throw new Error('Feed container not found');
  if (typeof fetchPage !== 'function') throw new TypeError('fetchPage must be a function');

  const { pageSize = 20, threshold = 300 } = options;
  let page = 1;
  let isLoading = false;
  let hasMore = true;

  function createSkeletons(count) {
    const frag = document.createDocumentFragment();
    for (let i = 0; i < count; i++) {
      const div = document.createElement('div');
      div.className = 'skeleton';
      div.style.cssText = 'height:200px;background:linear-gradient(90deg,#f0f0f0 25%,#e0e0e0 50%,#f0f0f0 75%);background-size:200% 100%;animation:shimmer 1.5s infinite;border-radius:8px;';
      frag.appendChild(div);
    }
    return frag;
  }

  // Add shimmer keyframes if not present
  if (!document.getElementById('skeleton-styles')) {
    const style = document.createElement('style');
    style.id = 'skeleton-styles';
    style.textContent = '@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }';
    document.head.appendChild(style);
  }

  async function loadMore() {
    if (isLoading || !hasMore) return;
    isLoading = true;
    const skeletons = createSkeletons(pageSize);
    container.appendChild(skeletons);

    try {
      const items = await fetchPage(page, pageSize);
      skeletons.remove();
      if (!items || items.length === 0) {
        hasMore = false;
        return;
      }
      items.forEach(item => container.appendChild(item));
      page++;
    } catch (err) {
      console.error('Feed load error:', err);
      skeletons.remove();
    } finally {
      isLoading = false;
    }
  }

  const sentinel = document.createElement('div');
  sentinel.style.height = '1px';
  container.appendChild(sentinel);

  const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) loadMore();
  }, { rootMargin: `${threshold}px` });
  observer.observe(sentinel);

  loadMore();
  return { loadMore, observer };
}

// Usage:
// createInfiniteFeed('#feed', async (page, size) => {
//   const res = await fetch(`/api/images?page=${page}&size=$50%`);
//   const data = await res.json();
//   return data.map(url => { const img = document.createElement('img'); img.src = url; return img; });
// });


Create a 2D canvas game loop with delta-time physics

Solution:
class GameEngine {
  constructor(canvasId, options = {}) {
    this.canvas = document.getElementById(canvasId);
    if (!this.canvas) throw new Error('Canvas not found: ' + canvasId);
    this.ctx = this.canvas.getContext('2d');
    this.entities = [];
    this.lastTime = 0;
    this.running = false;
    this.fps = 60;

    this.canvas.width = options.width || 800;
    this.canvas.height = options.height || 600;
    this.canvas.style.background = options.bg || '#ffeaa7';
  }

  addEntity(entity) {
    if (!entity.update || !entity.draw) {
      throw new TypeError('Entity must have update(dt) and draw(ctx) methods');
    }
    this.entities.push(entity);
    return this;
  }

  start() {
    this.running = true;
    requestAnimationFrame((t) => this.loop(t));
  }

  stop() {
    this.running = false;
  }

  loop(timestamp) {
    if (!this.running) return;
    const dt = Math.min((timestamp - this.lastTime) / 1000, 0.05); // Cap delta
    this.lastTime = timestamp;

    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    for (const entity of this.entities) {
      entity.update(dt, this.canvas.width, this.canvas.height);
      entity.draw(this.ctx);
    }

    requestAnimationFrame((t) => this.loop(t));
  }
}

// Usage:
// const engine = new GameEngine('game-canvas', { width: 800, height: 600 });
// engine.addEntity({ update(dt, w, h) { this.x += 100 * dt; }, draw(ctx) { ctx.fillRect(this.x, 100, 20, 20); }, x: 0 });
// engine.start();


Implement AABB collision detection for rectangular game entities

Solution:
function checkAABBCollision(a, b) {
  if (!a || !b) throw new Error('Both entities required for collision check');
  return (
    a.x < b.x + b.width &&
    a.x + a.width > b.x &&
    a.y < b.y + b.height &&
    a.y + a.height > b.y
  );
}

function resolveAABBOverlap(a, b) {
  const overlapX = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
  const overlapY = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);

  if (overlapX < overlapY) {
    const dir = a.x < b.x ? -1 : 1;
    a.x += (overlapX / 2) * dir;
    b.x -= (overlapX / 2) * dir;
  } else {
    const dir = a.y < b.y ? -1 : 1;
    a.y += (overlapY / 2) * dir;
    b.y -= (overlapY / 2) * dir;
  }
}

class PhysicsWorld {
  constructor() {
    this.bodies = [];
  }

  add(body) {
    if (typeof body.x !== 'number' || typeof body.y !== 'number') {
      throw new TypeError('Body must have numeric x and y properties');
    }
    this.bodies.push(body);
  }

  step() {
    for (let i = 0; i < this.bodies.length; i++) {
      for (let j = i + 1; j < this.bodies.length; j++) {
        if (checkAABBCollision(this.bodies[i], this.bodies[j])) {
          resolveAABBOverlap(this.bodies[i], this.bodies[j]);
          if (this.bodies[i].onCollision) this.bodies[i].onCollision(this.bodies[j]);
          if (this.bodies[j].onCollision) this.bodies[j].onCollision(this.bodies[i]);
        }
      }
    }
  }
}

// Usage:
// const world = new PhysicsWorld();
// world.add({ x: 0, y: 0, width: 32, height: 32, onCollision(other) { console.log('hit!'); } });
// world.step();


Build a sprite animation system with frame clipping and playback controls

Solution:
class SpriteAnimator {
  constructor(image, frameWidth, frameHeight, frameCount) {
    if (!(image instanceof HTMLImageElement)) throw new TypeError('Expected HTMLImageElement');
    this.image = image;
    this.frameWidth = frameWidth;
    this.frameHeight = frameHeight;
    this.frameCount = frameCount;
    this.currentFrame = 0;
    this.elapsed = 0;
    this.fps = 10;
    this.playing = true;
    this.loop = true;
  }

  update(dt) {
    if (!this.playing) return;
    this.elapsed += dt;
    const frameDuration = 1 / this.fps;
    if (this.elapsed >= frameDuration) {
      this.elapsed -= frameDuration;
      this.currentFrame++;
      if (this.currentFrame >= this.frameCount) {
        if (this.loop) this.currentFrame = 0;
        else { this.currentFrame = this.frameCount - 1; this.playing = false; }
      }
    }
  }

  draw(ctx, x, y, options = {}) {
    const sx = (this.currentFrame * this.frameWidth) % this.image.width;
    const sy = Math.floor((this.currentFrame * this.frameWidth) / this.image.width) * this.frameHeight;
    const scale = options.scale || 1;
    ctx.drawImage(
      this.image,
      sx, sy, this.frameWidth, this.frameHeight,
      x, y, this.frameWidth * scale, this.frameHeight * scale
    );
  }

  play() { this.playing = true; }
  pause() { this.playing = false; }
  reset() { this.currentFrame = 0; this.elapsed = 0; }
  setFrame(index) { this.currentFrame = Math.max(0, Math.min(index, this.frameCount - 1)); }
}

// Usage:
// const img = new Image();
// img.src = '/sprites/player.png';
// img.onload = () => {
//   const anim = new SpriteAnimator(img, 32, 32, 8);
//   // In game loop: anim.update(dt); anim.draw(ctx, 100, 100);
// };


Implement a tilemap renderer with camera scrolling and culling

Solution:
class TilemapRenderer {
  constructor(canvasId, tileSize = 32) {
    this.canvas = document.getElementById(canvasId);
    if (!this.canvas) throw new Error('Canvas not found');
    this.ctx = this.canvas.getContext('2d');
    this.tileSize = tileSize;
    this.camera = { x: 0, y: 0 };
    this.tiles = []; // 2D array of tile IDs
    this.tileset = new Map(); // ID -> color or image
  }

  loadMap(tiles) {
    if (!Array.isArray(tiles) || !tiles.every(row => Array.isArray(row))) {
      throw new TypeError('tiles must be a 2D array');
    }
    this.tiles = tiles;
  }

  registerTile(id, renderable) {
    this.tileset.set(id, renderable);
  }

  setCamera(x, y) {
    this.camera.x = x;
    this.camera.y = y;
  }

  render() {
    const cols = Math.ceil(this.canvas.width / this.tileSize) + 1;
    const rows = Math.ceil(this.canvas.height / this.tileSize) + 1;
    const startCol = Math.floor(this.camera.x / this.tileSize);
    const startRow = Math.floor(this.camera.y / this.tileSize);

    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        const tileRow = startRow + r;
        const tileCol = startCol + c;
        if (tileRow < 0 || tileRow >= this.tiles.length) continue;
        if (tileCol < 0 || tileCol >= this.tiles[tileRow].length) continue;

        const tileId = this.tiles[tileRow][tileCol];
        const screenX = c * this.tileSize - (this.camera.x % this.tileSize);
        const screenY = r * this.tileSize - (this.camera.y % this.tileSize);

        const renderable = this.tileset.get(tileId);
        if (typeof renderable === 'string') {
          this.ctx.fillStyle = renderable;
          this.ctx.fillRect(screenX, screenY, this.tileSize, this.tileSize);
        } else if (renderable instanceof HTMLImageElement) {
          this.ctx.drawImage(renderable, screenX, screenY, this.tileSize, this.tileSize);
        }
      }
    }
  }
}

// Usage:
// const renderer = new TilemapRenderer('game-canvas', 32);
// renderer.loadMap([[0,0,1],[0,1,1],[1,1,1]]);
// renderer.registerTile(0, '#e17055');
// renderer.registerTile(1, '#00b894');
// renderer.setCamera(100, 50);
// renderer.render();


Create a particle explosion effect on canvas for game feedback

Solution:
class ParticleSystem {
  constructor() {
    this.particles = [];
  }

  emit(x, y, options = {}) {
    const {
      count = 20,
      speed = 0.02,
      life = 1.0,
      colors = ['#fab1a0', '#74b9ff', '#6c5ce7'],
      size = 4,
      gravity = 200
    } = options;

    for (let i = 0; i < count; i++) {
      const angle = (Math.PI * 2 * i) / count + (Math.random() - 0.5) * 0.5;
      const velocity = speed * (0.5 + Math.random() * 0.5);
      this.particles.push({
        x, y,
        vx: Math.cos(angle) * velocity,
        vy: Math.sin(angle) * velocity,
        life,
        maxLife: life,
        color: colors[Math.floor(Math.random() * colors.length)],
        size: size * (0.5 + Math.random()),
        gravity
      });
    }
  }

  update(dt) {
    for (let i = this.particles.length - 1; i >= 0; i--) {
      const p = this.particles[i];
      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.vy += p.gravity * dt;
      p.life -= dt;
      if (p.life <= 0) this.particles.splice(i, 1);
    }
  }

  draw(ctx) {
    for (const p of this.particles) {
      const alpha = Math.max(0, p.life / p.maxLife);
      ctx.globalAlpha = alpha;
      ctx.fillStyle = p.color;
      ctx.beginPath();
      ctx.arc(p.x, p.y, p.size * alpha, 0, Math.PI * 2);
      ctx.fill();
    }
    ctx.globalAlpha = 1;
  }
}

// Usage:
// const particles = new ParticleSystem();
// particles.emit(400, 300, { count: 30, speed: 150, colors: ['#0984e3', '#ff6b6b', '#fdcb6e'] });
// // In game loop: particles.update(dt); particles.draw(ctx);