<commit_before># Memoizer Pattern

The result of pure function with one parameter, i.e. a function that has its return value only depending on the value
of the parameter with no side effect, can be stored in a cache to avoid re-computation of this value.

The Memoizer Pattern provided a reusable class `Memoizer` allowing add a cache to the computation
of a pure function.

## The memoizer pattern using inheritance

We can use the [Template Method](../templatemethod) pattern and inheritance to create a class that let users
overriding the method `compute()` while providing a method `memoize` that cache the result
of a computation.

```java
abstract class Memoizer<V, R> {
  private final HashMap<V, R> map = new HashMap<>();
    
  public final R memoize(V value) {
    return map.computeIfAbsent(value, this::compute);
  }
    
  protected abstract R compute(V value);
}
```

This is how it can be used:
```java
var memoizer = new Memoizer<Integer, Integer>() {<commit_msg>add a class diagram<commit_after># Memoizer Pattern

The result of pure function with one parameter, i.e. a function that has its return value only depending on the value
of the parameter with no side effect, can be stored in a cache to avoid re-computation of this value.

The Memoizer Pattern provided a reusable class `Memoizer` allowing add a cache to the computation
of a pure function.

## The memoizer pattern using inheritance

We can use the [Template Method](../templatemethod) pattern and inheritance to create a class that let users
overriding the method `compute()` while providing a method `memoize` that cache the result
of a computation.

```java
abstract class Memoizer<V, R> {
  private final HashMap<V, R> map = new HashMap<>();
    
  public final R memoize(V value) {
    return map.computeIfAbsent(value, this::compute);
  }
    
  protected abstract R compute(V value);
}
```

``mermaid
classDiagram
class Memoizer~V,R~ {
  <<abstract>>
  memoize(V value) R
  #compute(V value) R
}
```

This is how it can be used:
```java
var memoizer = new Memoizer<Integer, Integer>() {
{'fraction_non_alphanumeric': 0.08052073288331726, 'fraction_numerical': 0.0, 'mean_word_length': 4.30690537084399, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '105084', 'n_tokens_mistral': 597, 'n_tokens_neox': 582, 'n_words': 288}