functionalscript
Version:
FunctionalScript is a purely functional subset of JavaScript
45 lines (44 loc) • 1.22 kB
JavaScript
/**
* Repeats a monoid operation `n` times on the given element `a`.
* This function efficiently performs the operation using exponentiation by squaring.
*
* @template T The type of the elements in the monoid.
* @param monoid The monoid structure, including the identity and binary operation.
* @returns A function that takes an element `a` and a repetition count `n`,
* and returns the result of applying the operation `n` times.
*
* See also {@link https://en.wikipedia.org/wiki/Exponentiation_by_squaring}.
*
* @example
*
* ```ts
* const add: Monoid<number> = {
* identity: 0,
* operation: a => b => a + b,
* };
*
* const resultAdd = repeat(add)(2)(10n) // 20
*
* const concat: Monoid<string> = {
* identity: '',
* operation: a => b => a + b,
* };
*
* const resultConcat = repeat(concat)('ha')(3n) // 'hahaha'
* ```
*/
export const repeat = ({ identity, operation }) => (a) => (n) => {
let ai = a;
let ni = n;
let result = identity;
while (true) {
if ((ni & 1n) !== 0n) {
result = operation(result)(ai);
}
ni >>= 1n;
if (ni === 0n) {
return result;
}
ai = operation(ai)(ai);
}
};