Skip to content

Instantly share code, notes, and snippets.

@rkatic
rkatic / limited.js
Last active October 16, 2023 13:26
Elegant implementation of concurrency/speed limiter.
/** @param {number} n */
function semaphore (n) {
const resolvers = []
const pushToResolvers = resolve => { resolvers.push(resolve) }
/** @type {() => (Promise<void> | void)} */
const acquire = () => {
if (--n < 0) {
const identity = x => x
/**
* Creates a predicate function to check if a value is not seen before
*
* @param {function} [by = x=>x]
* @returns {function} predicate function
*
* @example
*
@rkatic
rkatic / re.js
Last active January 19, 2021 07:29
re - raw, multi-line, auto-escaping, composable, RegExp sexy creations
'use strict'
const objToStringMethod = Object.prototype.toString
const reRegExpChar = /[\\^$.*+?()[\]{}|]/g
const reUnescapedSpaces = /(?<!\\)\s+/g
const reHasSpace = /\s/
const compact = raw => reHasSpace.test(raw) ? raw.replace(reUnescapedSpaces, '') : raw
const escape = val => String(val).replace(reRegExpChar, '\\$&')
@rkatic
rkatic / timeout.js
Last active January 19, 2021 07:33
Simple promise based timeout implementation.
function timeout (ms, x) {
return new Promise((resolve, reject) => {
let timeoutId = setTimeout(() => {
timeoutId = null
reject('timeout')
}, ms)
const onSettle = () => {
if (timeoutId != null) {
clearTimeout(timeoutId)