metarhia / metautil

Metarhia utilities 🧰
https://metarhia.com
MIT License
100 stars 25 forks source link
hacktoberfest metarhia nodejs utilities

Metarhia utilities

ci status snyk npm version npm downloads/month npm downloads license

Usage

Async utilities

Class Collector

Async collection is an utility to collect needed keys and signalize on done.

Collect keys with .set method:

const ac = collect(['userName', 'fileName']);

setTimeout(() => ac.set('fileName', 'marcus.txt'), 100);
setTimeout(() => ac.set('userName', 'Marcus'), 200);

const result = await ac;
console.log(result);

Collect keys with .wait method from async or promise-returning function:

const ac = collect(['user', 'file']);

ac.wait('file', getFilePromisified, 'marcus.txt');
ac.wait('user', getUserPromisified, 'Marcus');

try {
  const result = await ac;
  console.log(result);
} catch (error) {
  console.error(error);
}

Collect keys with .take method from callback-last-error-first function:

const ac = collect(['user', 'file'], { timeout: 2000, exact: false });

ac.take('file', getFileCallback, 'marcus.txt');
ac.take('user', getUserCallback, 'Marcus');

const result = await ac;

Compose collectors (collect subkeys from multiple sources):

const dc = collect(['key1', 'key2', 'key3']);
const key1 = collect(['sub1']);
const key3 = collect(['sub3']);
dc.collect({ key1, key3 });
const result = await dc;

Complex example: compare Promise.allSettled + Promise.race vs Collector in next two examples:

// Collect 4 keys from different contracts with Promise.allSettled + Promise.race

const promise1 = new Promise((resolve, reject) => {
  fs.readFile('README.md', (err, data) => {
    if (err) return void reject(err);
    resolve(data);
  });
});
const promise2 = fs.promises.readFile('README.md');
const url = 'http://worldtimeapi.org/api/timezone/Europe';
const promise3 = fetch(url).then((data) => data.json());
const promise4 = new Promise((resolve) => {
  setTimeout(() => resolve('value4'), 50);
});
const timeout = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error('Timed out')), 1000);
});
const data = Promise.allSettled([promise1, promise2, promise3, promise4]);
try {
  const keys = await Promise.race([data, timeout]);
  const [key1, key2, key3, key4] = keys.map(({ value }) => value);
  const result = { key1, key2, key3, key4 };
  console.log(result);
} catch (err) {
  console.log(err);
}

Compare with:

// Collect 4 keys from different contracts with Collector

const dc = collect(['key1', 'key2', 'key3', 'key4'], { timeout: 1000 });

dc.take('key1', fs.readFile, 'README.md');
dc.wait('key2', fs.promises.readFile, 'README.md');
const url = 'http://worldtimeapi.org/api/timezone/Europe';
dc.wait(
  'key3',
  fetch(url).then((data) => data.json()),
);
setTimeout(() => dc.set('key4', 'value4'), 50);

try {
  const result = await dc;
  console.log(result);
} catch (err) {
  console.log(err);
}

Crypto utilities

const x509 = new crypto.X509Certificate(cert);
const domains = metautil.getX509names(x509);

Datetime utilities

Error utilities

File system utilities

HTTP utilities

Network utilities

Objects utilities

Class Pool

const pool = new metautil.Pool();
pool.add({ a: 1 });
pool.add({ a: 2 });
pool.add({ a: 3 });

if (pool.isFree(obj1)) console.log('1 is free');
const item = await pool.capture();
if (pool.isFree(obj1)) console.log('1 is captured');
const obj = await pool.next();
// obj is { a: 2 }
pool.release(item);

Array utilities

sample(array: Array<unknown>): unknown

const cards = ['🂡', '🃒', '🂮', '🂷', '🃚'];
const card = sample(cards);

shuffle(array: Array<unknown>): Array<unknown>

const players = [{ id: 10 }, { id: 12 }, { id: 15 }];
const places = shuffle(players);

projection(source: object, fields: Array<string>): Array<unknown>

const player = { name: 'Marcus', score: 1500, socket };
const playerState = projection(player, ['name', 'score']);

Class Semaphore

const options = { concurrency: 3, size: 4, timeout: 1500 };
const semaphore = new Semaphore(options);
await semaphore.enter();
// Do something
semaphore.leave();

Strings utilities

Units utilities

const size = bytesToSize(100000000);
const bytes = sizeToBytes(size);
console.log({ size, bytes });
// { size: '100 MB', bytes: 100000000 }
Symbol zeros Unit
yb 24 yottabyte
zb 21 zettabyte
eb 18 exabyte
pb 15 petabyte
tb 12 terabyte
gb 9 gigabyte
mb 6 megabyte
kb 3 kilobyte

Class EventEmitter

EventEmitter utilities

const ee = new metautil.EventEmitter();
setTimeout(() => ee.emit('name3', 'value'), 100);
const result = await metautil.once(ee, 'name3');

License & Contributors

Copyright (c) 2017-2024 Metarhia contributors. Metautil is MIT licensed.\ Metautil is a part of Metarhia technology stack.