Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Move async utils from metasync #270

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 84 additions & 1 deletion lib/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,87 @@ const timeoutify = (promise, msec) =>
);
});

module.exports = { toBool, timeout, delay, timeoutify };
const throttle = (timeout, fn, ...args) => {
let timer;
let wait = false;

const execute = args
? (...pars) => (pars ? fn(...args, ...pars) : fn(...args))
: (...pars) => (pars ? fn(...pars) : fn());

const delayed = (...pars) => {
timer = undefined;
if (wait) execute(...pars);
};

const throttled = (...pars) => {
if (!timer) {
timer = setTimeout(delayed, timeout, ...pars);
wait = false;
execute(...pars);
}
wait = true;
};

return throttled;
};

const debounce = (timeout, fn, ...args) => {
let timer;

const debounced = () => (args ? fn(...args) : fn());

const wrapped = () => {
if (timer) clearTimeout(timer);
timer = setTimeout(debounced, timeout);
};

return wrapped;
};

const callbackify =
(fn) =>
(...args) => {
const callback = args.pop();
fn(...args)
.then((value) => {
callback(null, value);
})
.catch((reason) => {
callback(reason);
});
};

const asyncify =
(fn) =>
(...args) => {
const callback = args.pop();
setTimeout(() => {
let result;
try {
result = fn(...args);
} catch (error) {
return void callback(error);
}
callback(null, result);
}, 0);
};

const promisify =
(fn) =>
(...args) =>
new Promise((resolve, reject) =>
fn(...args, (err, data) => (err ? reject(err) : resolve(data))),
);

module.exports = {
toBool,
timeout,
delay,
timeoutify,
throttle,
debounce,
callbackify,
asyncify,
promisify,
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"test": "npm run lint && npm run types && node --test --test-reporter=tap",
"types": "tsc -p tsconfig.json",
"lint": "eslint . && prettier --check \"**/*.js\" \"**/*.json\" \"**/*.md\" \"**/*.ts\"",
"fix": "eslint . --fix && prettier --write \"**/*.js\" \"**/*.json\" \"**/*.md\" \"**/*.ts\""
"fix": "eslint . --fix; prettier --write \"**/*.js\" \"**/*.json\" \"**/*.md\" \"**/*.ts\""
},
"devDependencies": {
"@types/node": "^22.5.1",
Expand Down
210 changes: 209 additions & 1 deletion test/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

const test = require('node:test');
const assert = require('node:assert');
const { toBool, timeout, delay, timeoutify } = require('..');
const metautil = require('..');
const { toBool, timeout, delay } = metautil;
const { timeoutify, throttle, debounce } = metautil;
const { callbackify, asyncify, promisify } = metautil;

test('Async: toBool', async () => {
const success = await Promise.resolve('success').then(...toBool);
Expand Down Expand Up @@ -67,3 +70,208 @@ test('Async: timeoutify', async () => {
assert.ifError(new Error('Should not be executed'));
}
});

test('Async: throttle', async () => {
let resolve = null;
const promise = new Promise((r) => {
resolve = r;
});

let callCount = 0;

const fn = (arg1, arg2, ...otherArgs) => {
assert.strictEqual(arg1, 'someVal');
assert.strictEqual(arg2, 4);
assert.deepEqual(otherArgs, []);
callCount++;
assert.ok(callCount <= 2);
if (callCount === 2) resolve();
};

const throttledFn = throttle(1, fn, 'someVal', 4);

throttledFn();
assert.strictEqual(callCount, 1);
throttledFn();
assert.strictEqual(callCount, 1);
throttledFn();
assert.strictEqual(callCount, 1);
return promise;
});

test('Async: throttle merge args', async () => {
let resolve = null;
const promise = new Promise((r) => {
resolve = r;
});

let callCount = 0;

const fn = (arg1, arg2, ...otherArgs) => {
assert.strictEqual(arg1, 'someVal');
assert.strictEqual(arg2, 4);
assert.deepEqual(otherArgs, ['str']);
callCount++;
assert.ok(callCount <= 2);
if (callCount === 2) resolve();
};

const throttledFn = throttle(1, fn, 'someVal', 4);

throttledFn('str');
assert.strictEqual(callCount, 1);
throttledFn('str');
assert.strictEqual(callCount, 1);
throttledFn('str');
assert.strictEqual(callCount, 1);
return promise;
});

test('Async: throttle without arguments', async () => {
let resolve = null;
const promise = new Promise((r) => {
resolve = r;
});

let callCount = 0;

const fn = (...args) => {
assert.deepEqual(args, []);
callCount++;
assert.ok(callCount <= 2);
if (callCount === 2) resolve();
};

const throttledFn = throttle(1, fn);

throttledFn();
assert.strictEqual(callCount, 1);
throttledFn();
assert.strictEqual(callCount, 1);
throttledFn();
assert.strictEqual(callCount, 1);
return promise;
});

test('Async: debounce', async () => {
let resolve = null;
const promise = new Promise((r) => {
resolve = r;
});

let count = 0;

const fn = (arg1, arg2, ...otherArgs) => {
assert.strictEqual(arg1, 'someVal');
assert.strictEqual(arg2, 4);
assert.deepEqual(otherArgs, []);
count++;
assert.strictEqual(count, 1);
resolve();
};

const debouncedFn = debounce(1, fn, 'someVal', 4);

debouncedFn();
assert.strictEqual(count, 0);
debouncedFn();
assert.strictEqual(count, 0);
return promise;
});

test('Async: debounce without arguments', async () => {
let resolve = null;
const promise = new Promise((r) => {
resolve = r;
});

let count = 0;

const fn = (...args) => {
assert.deepEqual(args, []);
count++;
assert.strictEqual(count, 1);
resolve();
};

const debouncedFn = debounce(1, fn);

debouncedFn();
assert.strictEqual(count, 0);
debouncedFn();
assert.strictEqual(count, 0);
return promise;
});

test('Callbackify: Promise to callback-last', async () => {
let resolve = null;
const promise = new Promise((r) => {
resolve = r;
});

const promiseReturning = () => Promise.resolve('result');
const asyncFn = callbackify(promiseReturning);

asyncFn((err, value) => {
assert.ifError(err);
assert.strictEqual(value, 'result');
resolve();
});

return promise;
});

test('Asyncify: sync function to callback-last', async () => {
let resolve = null;
const promise = new Promise((r) => {
resolve = r;
});

const fn = (par) => par;
const asyncFn = asyncify(fn);

asyncFn('result', (err, value) => {
if (err) assert.ifError(err);
assert.strictEqual(value, 'result');
resolve();
});

return promise;
});

test('Promisify: callback-last to Promise', async () => {
const id = 100;
const data = { key: 'value' };

const getDataAsync = (dataId, callback) => {
assert.strictEqual(dataId, id);
callback(null, data);
};

const getDataPromise = promisify(getDataAsync);

try {
const result = await getDataPromise(id);
assert.strictEqual(result, data);
} catch (err) {
assert.ifError(err);
}
});

test('Promisify: callback-last to Promise throw', async () => {
const id = 100;

const getDataAsync = (dataId, callback) => {
assert.strictEqual(dataId, id);
callback(new Error('Data not found'));
};

const getDataPromise = promisify(getDataAsync);

try {
const result = await getDataPromise(id);
assert.notOk(result);
} catch (err) {
assert.ok(err);
}
});
Loading