Code Explainers

Code explainers tagged #memoization

python
from functools import lru_cache
import math
 
 

Memoizing number theory with lru_cache

memoization number-theory caching
Intermediate 8 steps
ruby
class ReportGenerator
  def initialize(account, period)
    @account = account
    @period = period

Memoized report metrics in Ruby in Rails

memoization query-composition service-object
Intermediate 7 steps
php
function memoize(callable $fn): callable
{
    $cache = [];
 

How memoization works in PHP closures

memoization closures higher-order-functions
Intermediate 8 steps
ruby
require "csv"
 
class SalesReport
  def initialize(path)

Aggregating CSV sales data in Ruby

data-aggregation memoization group_by
Intermediate 6 steps
rust
use std::collections::HashMap;
 
pub struct Memoizer<K, V, F> {
    cache: HashMap<K, V>,

A generic memoizer in Rust

memoization generics caching
Intermediate 6 steps
java
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.math.BigInteger;
 

A thread-safe memoized factorial cache

memoization thread-safety caching
Intermediate 6 steps
python
from functools import wraps
 
 
def memoize(func):

Building a memoize decorator in Python

decorators closures memoization
Intermediate 5 steps
javascript
import { useMemo, useState } from 'react';
 
function ProductList({ products }) {
  const [query, setQuery] = useState('');

Memoizing a filtered list in React

memoization derived-state filtering
Intermediate 8 steps
ruby
module Fibonacci
  CACHE = Hash.new do |cache, n|
    cache[n] = cache[n - 1] + cache[n - 2]
  end

Memoizing Fibonacci with a Hash default block

memoization recursion hash-default
Intermediate 5 steps
ruby
class ProductCatalog
  def featured_products
    Rails.cache.fetch("catalog/featured_products", expires_in: 12.hours) do
      Product.where(featured: true)

Caching patterns with Rails.cache.fetch

caching cache-keys expiry
Intermediate 5 steps