Skip to content

Instantly share code, notes, and snippets.

export type AtLeastOne<T> = [T, ...T[]];
export function groupByUsing<V, K extends keyof V, U>(
iterable: Iterable<V>,
key: K | ((value: V, index: number) => V[K]),
callback: (value: V, index: number) => U,
): Map<V[K], AtLeastOne<U>> {
const mapper = typeof key !== "function" ? (v: V) => v[key] : key;
const map = new Map<V[K], AtLeastOne<U>>();
@friendlyanon
friendlyanon / explode.ts
Last active February 27, 2022 03:38
PHP's explode function implemented in JavaScript
/**
* Explode implementation. The inputs to this function are not validated, use
* {@link explode} for inputs that might not meet the requirements.
*
* @param delimiter Non-empty string
* @param string
* @param limit Integer in the range of [2 - 4294967295]
*/
export function explodeUnchecked(
delimiter: string,
function drop(iterator, amount) {
for (let i = 0; !(i >= amount); ++i) {
if (iterator.next().done) {
break;
}
}
return iterator;
}
function once(fn) {
const { name, length } = fn;
let called = false;
// match .name of argument
const wrapped = {
[name]() {
if (!called) {
called = true;
fn.apply(this, arguments);
export const groupByUsing = (iterable, key, callback) => {
const mapper = typeof key !== "function" ? x => x[key] : key;
const map = new Map();
let i = -1;
for (const value of iterable) {
const mappedKey = mapper(value, ++i, key);
const mappedValue = callback(value, i, key);
const group = map.get(mappedKey);
async function concurrentWorker(context, callback) {
const { queue } = context;
const abortToken = Symbol();
while (context.ok) {
const { done, value } = queue.next();
if (done) {
context.ok = false;
return;
}
export const IndexableMap = class extends Map {
constructor(iterable) {
super();
this._values = [];
if (iterable != null) {
for (const [key, value] of iterable) {
this.set(key, value);
}
}
}
function* parseNdjson(ndjson) {
let i = 0;
do {
const newline = ndjson.indexOf("\n", i);
const string = newline === -1 ? ndjson.slice(i) : ndjson.slice(i, newline);
const json = string.trim();
if (json) {
yield JSON.parse(json);
}
i = newline + 1;
const map = {
"-1": "💥",
"0": "🟦",
};
const inRange = (number, max) => 0 <= number && number < max;
const neighbors = [
[-1, -1], [-1, 0], [-1, 1],
[0, -1], [ 0, 1],
/* use sleep from below, or bring your own */
// export const sleep = millis => new Promise(_ => setTimeout(_, millis));
async function impl(sentinel, func, interval, args) {
for (; !sentinel.aborted; await sleep(interval)) {
await func(...args);
}
}
export default function runAtIntervals(func, interval, ...args) {