Skip to content

Instantly share code, notes, and snippets.

@leoschur
leoschur / groupArrayByAccessor.js
Created December 20, 2021 17:03
groupBy function to group a given array by a given accessor and return the grouped values as a js Map
/**
* group an array by accessor
* @param arr array of elements
* @param accessor called on element, must return a value from the elements after which they are to be grouped
* @returns Map where keys are defined by accessor function and values are an array of elements
*/
const groupBy = (a, accessor) => {
if (!Array.isArray(a)) throw 'param a is not an array';
if (typeof(accessor) != 'function') throw 'param accessor is not a function';
return a.reduce(
@leoschur
leoschur / squareandmultiply.js
Created February 7, 2021 13:31
square and multiply algorithm
function sqm(base, exponent, mod) {
let ze = 1; let a = base;
while (exponent) {
if (exponent & 1) ze = (ze * a) % mod;
a = (a * a) % mod;
exponent = exponent >> 1;
// console.log("Ze: " + ze + " A: " + a);
}
return ze;
}