diff --git a/workspace/mauss/src/core/README.md b/workspace/mauss/src/core/README.md index e1a3a7f..9af7404 100644 --- a/workspace/mauss/src/core/README.md +++ b/workspace/mauss/src/core/README.md @@ -44,6 +44,14 @@ A function to check for values equality between two variables. This will work fo A function that accepts a function and returns the same function with the order of parameters reversed. This can be used in conjunction with `compare` methods to sort the items in ascending values. +## `memory` + +```typescript +export function memory(initial: T, fn: (previous: T) => void): (updated: T) => T; +``` + +A higher-order function that runs a callback function only when the `initial`/previous and `updated` are different. This is useful for updating the state of a component only when the value has changed. + ## `pipe` A type-safe higher-order function that accepts any number of arguments, it returns a function with the parameters of the first function passed and a return type/value of the last function. diff --git a/workspace/mauss/src/core/standard/index.ts b/workspace/mauss/src/core/standard/index.ts index c02ab6d..3375c15 100644 --- a/workspace/mauss/src/core/standard/index.ts +++ b/workspace/mauss/src/core/standard/index.ts @@ -55,6 +55,16 @@ export function inverse(fn: Function) { return (...parameters: Reversed): Returned => fn(...parameters.reverse()); } +export function memory(initial: T, fn: AnyFunction<[previous: T], void>) { + let previous = initial; + return (updated: T) => { + if (!identical(previous, updated)) { + fn(previous), (previous = updated); + } + return updated; + }; +} + /** * regexp - implementation of global RegExp constructor with escaped pattern * @param pattern passed in the form of string literal