Skip to content

Instantly share code, notes, and snippets.

View HichamBenjelloun's full-sized avatar

Hicham Benjelloun HichamBenjelloun

View GitHub Profile
@HichamBenjelloun
HichamBenjelloun / unarrow.js
Last active June 25, 2020 00:02
Transforming an arrow function into a regular function in JavaScript
const unarrow = arrowFunc => {
const arrowFuncDefinition = arrowFunc.toString();
const hasEnclosingBraces = arrowFuncDefinition.indexOf('}') === arrowFuncDefinition.length - 1;
const newDefinition =
`return function${
hasEnclosingBraces ?
arrowFuncDefinition.replace('=>', '') :
arrowFuncDefinition.replace('=>', '{return ') + '}'
}`;
@HichamBenjelloun
HichamBenjelloun / sum.js
Last active June 17, 2024 09:12
Generic sum function
const sum = (...args) =>
Object.assign(
sum.bind(null, ...args),
{valueOf: () => args.reduce((acc, cur) => acc + cur, 0)}
);
export default sum;
@HichamBenjelloun
HichamBenjelloun / subIterable.js
Last active March 19, 2021 23:36
A function that creates a generator over a subset of a specified iterable using a condition
const filter = function* (iterable, cond) {
const iterator = iterable[Symbol.iterator]();
let cursor = iterator.next();
do {
const {value} = cursor;
if (cond(value)) {
yield value;
}
} while (!(cursor = iterator.next()).done);
};
@HichamBenjelloun
HichamBenjelloun / parseCookies.js
Last active June 25, 2020 18:27
A function that parses a string representation of a list of cookies into an object
const SEP_KEYVAL = '='; // represents a separator between a key and the corresponding value
const SEP_COOKIES = ';'; // represents a separator between two adjacent cookies
const parseKeyValuePair = keyValuePairStr => {
const [key, value] =
keyValuePairStr
.trimStart()
.split(SEP_KEYVAL);
return [key, decodeURIComponent(value)];
@HichamBenjelloun
HichamBenjelloun / sieveOfEratosthenes.js
Last active July 10, 2020 14:51
Sieve of Eratosthenes
/**
* Initializes an empty sieve
*
* @returns {{primes: Set<number>, crossed: Set<number>, greatestComputedMultiples: Map<number, number>}}
*/
const createSieve = () => ({
primes: new Set(),
crossed: new Set(),
greatestComputedMultiples: new Map(), // `prime` -> greatest computed multiple for `prime`
});
@HichamBenjelloun
HichamBenjelloun / curry.js
Last active July 26, 2020 01:05
Currying functions
/**
* Transforms a function of the form:
* fn = (p1, ..., pN) => f(p1, ...pN)
* to its curried form:
* curried = p1 => p2 => ... => pN => fn(p1, p2, ..., pN);
*
* @param fn
* @returns the curried form of fn
*/
const curry = fn =>
@HichamBenjelloun
HichamBenjelloun / memoize-recursive.js
Last active January 2, 2022 21:38
Memoizing recursive functions
const memoizeFactory = hashFn => fn => {
const memoize = fn => {
const cache = {};
return (...args) => {
const key = hashFn(args);
if (key in cache) {
return cache[key];
}
@HichamBenjelloun
HichamBenjelloun / rearrange.js
Last active April 5, 2021 13:51
Rearrange object structure
import _ from 'lodash';
const isPlainObject = value =>
value === Object(value) &&
!Array.isArray(value);
function* leaves(node, path = []) {
if (!isPlainObject(node)) {
return yield {value: node, path};
@HichamBenjelloun
HichamBenjelloun / max-concurrent-promises.js
Last active April 30, 2021 23:56
Limiting the number of concurrent running promises
let runningPromiseCount = 0;
const examplePromiseRunnerQueue = new Array(10)
.fill(0)
.map((_, idx) => idx)
.map((idx) => {
return async () => {
console.log(
`[${new Date().toISOString()}] Promise ${idx} will run! \n# of running promises: ${runningPromiseCount}`
);
@HichamBenjelloun
HichamBenjelloun / max-concurrent-promises-gen.js
Created May 1, 2021 13:49
Limiting the number of concurrent running promises streamed via a generator
const DEFAULT_MAX_CONCURRENT_PROMISES = 5;
/**
* Runs a stream of promises and ensures only `max` promises are run at a time
* @param {*} promiseRunnerGen
* @param {*} max
*/
const run = (promiseRunnerGen, max = DEFAULT_MAX_CONCURRENT_PROMISES) => {
const iterator = promiseRunnerGen();
let runningPromiseCount = 0;