Skip to content

Instantly share code, notes, and snippets.

View HichamBenjelloun's full-sized avatar

Hicham Benjelloun HichamBenjelloun

View GitHub Profile
@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 / 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 / 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 / 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 ') + '}'
}`;