New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

swiss-ak

Package Overview
Dependencies
Maintainers
1
Versions
70
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

swiss-ak - npm Package Compare versions

Comparing version 1.4.0 to 1.5.0

src/tools/ArrayUtils.ts

277

dist/index.d.ts

@@ -220,3 +220,3 @@ declare type Partial$1<T> = {

declare type CustomEntryDict<T, TName> = {
[K in keyof T]: (durations: TimerDurations<TName>) => number;
[K in keyof T]?: (durations: TimerDurations<TName>) => number;
};

@@ -386,2 +386,191 @@ interface CustomEntryObj {

declare const getDeferred: <T extends unknown>() => DeferredPromise<T>;
/**
* An alias for Promise.all
*/
declare const all: <T extends unknown>(promises: Promise<T>[]) => Promise<any>;
/**
* Like Promise.all, but limits the numbers of concurrently running items.
*
* Takes an array of functions (that return Promises), rather than an array of Promises
*
* ```typescript
* import { PromiseUtils, timer, ms, seconds } from 'swiss-ak';
*
* const give = async (delay: ms, result: number, label: string) => {
* await waitFor(delay);
* timer.end(label);
* return result;
* };
*
* timer.start('allLimit', 'a', 'b', 'c', 'd');
*
* const results = PromiseUtils.allLimit<number>(2, [
* give(seconds(5), 1, 'a'),
* give(seconds(5), 2, 'b'),
* give(seconds(5), 3, 'c'),
* give(seconds(5), 4, 'd')
* ]);
*
* timer.end('allLimit');
*
* console.log(results); // [ 1, 2, 3, 4 ]
*
* timer.log();
* // Times:
* // allLimit: 10s
* // a: 5s
* // b: 5s
* // c: 10s
* // d: 10s
* ```
*/
declare const allLimit: <T extends unknown>(limit: number, items: ((index: number) => Promise<T>)[], noThrow?: boolean) => Promise<T[]>;
/**
* Run an async function against each item in an array
*
* ```typescript
* import { PromiseUtils, ms, seconds, wait } from 'swiss-ak';
*
* const arr = [1, 2, 3, 4];
*
* await PromiseUtils.each<number>(arr, async (val: number) => {
* await wait(seconds(2));
* sendToSomewhere(val);
* });
* console.log(''); // after 2 seconds
* ```
*/
declare const each: <Ti extends unknown>(items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<any>) => Promise<any>;
/**
* Run an async function against each item in an array, limiting the number of items that can run concurrently.
*
* See PromiseUtils.allLimit for information about limited functions.
*
* ```typescript
* import { PromiseUtils, ms, seconds, wait } from 'swiss-ak';
*
* const arr = [1, 2, 3, 4];
*
* await PromiseUtils.eachLimit<number>(2, arr, async (val: number) => {
* await wait(seconds(2));
* sendToSomewhere(val);
* });
* console.log(''); // after 4 seconds
* ```
*/
declare const eachLimit: <Ti extends unknown>(limit: number, items: Ti[], func: (item?: Ti, index?: number, array?: Ti[]) => Promise<any>) => Promise<any>;
/**
* Run an async map function against each item in an array, mapping the results to a returned array
*
* ```typescript
* import { PromiseUtils, ms, seconds, wait } from 'swiss-ak';
*
* const arr = [1, 2, 3, 4];
*
* const mapped = await PromiseUtils.map<number>(arr, async (val: number) => {
* await wait(seconds(2));
* return val * 2;
* });
*
* console.log(mapped); // [2, 4, 6, 8] (after 2 seconds)
* ```
*/
declare const map: <Ti extends unknown, To extends unknown>(items: Ti[], func: (item?: Ti, index?: number, array?: Ti[]) => Promise<To>) => Promise<To[]>;
/**
* Run an async map function against each item in an array, mapping the results to a returned array, and limiting the number of items that can run concurrently.
*
* See PromiseUtils.allLimit for information about limited functions.
*
* ```typescript
* import { PromiseUtils, ms, seconds, wait } from 'swiss-ak';
*
* const arr = [1, 2, 3, 4];
*
* const mapped = await PromiseUtils.mapLimit<number>(2, arr, async (val: number) => {
* await wait(seconds(2));
* return val * 2;
* });
*
* console.log(mapped); // [2, 4, 6, 8] (after 4 seconds)
* ```
*/
declare const mapLimit: <Ti extends unknown, To extends unknown>(limit: number, items: Ti[], func: (item?: Ti, index?: number, array?: Ti[]) => Promise<To>) => Promise<To[]>;
/**
* Like Promise.all, but pass/receive objects rather than arrays
*
* ```typescript
* import { PromiseUtils, timer, ms, seconds } from 'swiss-ak';
*
* const give = async (delay: ms, result: number, label: string) => {
* await waitFor(delay);
* timer.end(label);
* return result;
* };
*
* timer.start('allObj', 'a', 'b', 'c');
*
* const results = PromiseUtils.allObj<number>({
* a: give(seconds(10), 1, 'a'),
* b: give(seconds(15), 2, 'b'),
* c: give(seconds(20), 3, 'c')
* });
*
* timer.end('allObj');
*
* console.log(results); // { a: 1, b: 2, c: 3 }
*
* timer.log();
* // Times:
* // allObj: 20s
* // a: 10s
* // b: 15s
* // c: 20s
* ```
*/
declare const allObj: <T extends unknown>(input: {
[key: string]: Promise<T>;
}) => Promise<{
[key: string]: T;
}>;
/**
* A mix of allObj and allLimit.
*
* Takes an array of functions (that return Promises), and limits the numbers of concurrently running items.
*
* ```typescript
* import { PromiseUtils, timer, ms, seconds } from 'swiss-ak';
*
* const give = async (delay: ms, result: number, label: string) => {
* await waitFor(delay);
* timer.end(label);
* return result;
* };
*
* timer.start('allLimitObj', 'a', 'b', 'c', 'd');
*
* const results = PromiseUtils.allLimitObj<number>(2, {
* a: give(seconds(5), 1, 'a'),
* b: give(seconds(5), 2, 'b'),
* c: give(seconds(5), 3, 'c'),
* d: give(seconds(5), 4, 'd')
* });
*
* timer.end('allLimitObj');
*
* console.log(results); // { a: 1, b: 2, c: 3, d: 4 }
*
* timer.log();
* // Times:
* // allLimitObj: 10s
* // a: 5s
* // b: 5s
* // c: 10s
* // d: 10s
* ```
*/
declare const allLimitObj: <T extends unknown>(limit: number, input: {
[key: string]: (index: number) => Promise<T>;
}, noThrow?: boolean) => Promise<{
[key: string]: T;
}>;
declare const PromiseUtils: {

@@ -401,3 +590,3 @@ getDeferred: <T extends unknown>() => DeferredPromise<T>;

allLimitObj: <T_4 extends unknown>(limit: number, input: {
[key: string]: (index: number) => Promise<T_4>;
[key: string]: (index: number) => Promise<T>;
}, noThrow?: boolean) => Promise<{

@@ -408,2 +597,84 @@ [key: string]: T_4;

export { CENTURY, CustomEntryDict, DAY, DECADE, DeferredPromise, HOUR, KeysOnly, MILLENNIUM, MILLISECOND, MINUTE, MONTH, Numbered, Partial$1 as Partial, ProgressBarOptions, PromiseUtils, SECOND, WEEK, YEAR, centuries, century, day, days, decade, decades, getDeferred, getProgressBar, getTimer, hour, hours, interval, millennium, millenniums, milliseconds, minute, minutes, month, months, ms, printLn, progressBar, second, seconds, stopInterval, timer, times, wait, waitEvery, waitFor, waitUntil, waiters, week, weeks, year, years };
/**
* Returns an array of the given length, where each value is equal to it's index
* e.g. [0, 1, 2, ..., length]
*
* ```typescript
* range(3); // [0, 1, 2]
* range(5); // [0, 1, 2, 3, 4]
* range(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
* ```
*/
declare const range: (length?: number) => number[];
/**
* Converts multiple arrays into an array of 'tuples' for each value at the corresponding indexes.
*
* Limited to the length of the shortest provided array
*
* Inspired by python's 'zip'
*
* > Note: The typing of this is messy - needs improvement
*
* ```typescript
* zip([1, 2, 3, 4], ['a', 'b', 'c']); // [ [1, 'a'], [2, 'b'], [3, 'c'] ]
* ```
*/
declare const zip: <T1 = undefined, T2 = undefined, T3 = undefined, T4 = undefined, T5 = undefined>(arrs_0?: T1[], arrs_1?: T2[], arrs_2?: T3[], arrs_3?: T4[], arrs_4?: T5[]) => [T1, T2, T3, T4, T5][];
/**
* Sort an array by a mapped form of the values, but returning the initial values
*
* ```typescript
* sortByMapped(['2p', '3p', '1p'], (v) => Number(v.replace('p', ''))); // ['1p', '2p', '3p']
* sortByMapped(
* ['2p', '3p', '1p'],
* (v) => Number(v.replace('p', '')),
* (a, b) => b - a
* ); // ['3p', '2p', '1p']
* ```
*/
declare const sortByMapped: <T, M>(arr: T[], mapFn: (value: T, index: number, array: T[]) => M, sortFn?: (a: M, b: M) => number) => T[];
/**
* Returns a clone of the provided array with it's items in a random order
*
* ```typescript
* randomise([1, 2, 3, 4, 5, 6]); // [ 5, 3, 4, 1, 2, 6 ]
* randomise([1, 2, 3, 4, 5, 6]); // [ 5, 1, 3, 2, 4, 6 ]
* randomise([1, 2, 3, 4, 5, 6]); // [ 6, 1, 4, 5, 2, 3 ]
* randomise([1, 2, 3, 4, 5, 6]); // [ 1, 4, 5, 2, 3, 6 ]
* randomise([1, 2, 3, 4, 5, 6]); // [ 2, 6, 1, 3, 4, 5 ]
* ```
*/
declare const randomise: <T>(arr: T[]) => T[];
/**
* Returns a new array with the order reversed without affecting original array
*
* ```typescript
* const arr1 = [1, 2, 3];
* arr1 // [1, 2, 3]
* arr1.reverse(); // [3, 2, 1]
* arr1 // [3, 2, 1]
*
* const arr2 = [1, 2, 3];
* arr2 // [1, 2, 3]
* reverse(arr2); // [3, 2, 1]
* arr2 // [1, 2, 3]
* ```
*/
declare const reverse: <T>(arr: T[]) => T[];
declare const ArrayUtils_range: typeof range;
declare const ArrayUtils_zip: typeof zip;
declare const ArrayUtils_sortByMapped: typeof sortByMapped;
declare const ArrayUtils_randomise: typeof randomise;
declare const ArrayUtils_reverse: typeof reverse;
declare namespace ArrayUtils {
export {
ArrayUtils_range as range,
ArrayUtils_zip as zip,
ArrayUtils_sortByMapped as sortByMapped,
ArrayUtils_randomise as randomise,
ArrayUtils_reverse as reverse,
};
}
export { ArrayUtils, CENTURY, CustomEntryDict, DAY, DECADE, DeferredPromise, HOUR, KeysOnly, MILLENNIUM, MILLISECOND, MINUTE, MONTH, Numbered, Partial$1 as Partial, ProgressBarOptions, PromiseUtils, SECOND, WEEK, YEAR, all, allLimit, allLimitObj, allObj, centuries, century, day, days, decade, decades, each, eachLimit, getDeferred, getProgressBar, getTimer, hour, hours, interval, map, mapLimit, millennium, millenniums, milliseconds, minute, minutes, month, months, ms, printLn, progressBar, randomise, range, reverse, second, seconds, sortByMapped, stopInterval, timer, times, wait, waitEvery, waitFor, waitUntil, waiters, week, weeks, year, years, zip };

@@ -22,2 +22,3 @@ var __defProp = Object.defineProperty;

__export(src_exports, {
ArrayUtils: () => ArrayUtils_exports,
CENTURY: () => CENTURY,

@@ -35,5 +36,11 @@ DAY: () => DAY,

YEAR: () => YEAR,
all: () => all,
allLimit: () => allLimit,
allLimitObj: () => allLimitObj,
allObj: () => allObj,
centuries: () => centuries,
days: () => days,
decades: () => decades,
each: () => each,
eachLimit: () => eachLimit,
getDeferred: () => getDeferred,

@@ -44,2 +51,4 @@ getProgressBar: () => getProgressBar,

interval: () => interval,
map: () => map,
mapLimit: () => mapLimit,
millenniums: () => millenniums,

@@ -51,3 +60,7 @@ milliseconds: () => milliseconds,

progressBar: () => progressBar_exports,
randomise: () => randomise,
range: () => range,
reverse: () => reverse,
seconds: () => seconds,
sortByMapped: () => sortByMapped,
stopInterval: () => stopInterval,

@@ -62,3 +75,4 @@ timer: () => timer,

weeks: () => weeks,
years: () => years
years: () => years,
zip: () => zip
});

@@ -244,3 +258,3 @@ module.exports = __toCommonJS(src_exports);

} else {
cEntries = Object.entries(customEntries).map(([label, func]) => ({ label, duration: func(durations) }));
cEntries = Object.entries(customEntries).map(([label, func]) => ({ label, duration: (func || (() => 0))(durations) || 0 }));
}

@@ -429,7 +443,2 @@ console.log(wrapperFn(chalk.dim(" " + "\u23AF".repeat(longest))));

};
var objectify = async (func, input) => {
const keys = Object.keys(input);
const results = await func(Object.values(input));
return Object.fromEntries(keys.map((key, index) => [key, results[index]]));
};
var each = async (items, func) => {

@@ -461,2 +470,7 @@ await Promise.all(items.map((item, index, array) => func(item, index, array)));

);
var objectify = async (func, input) => {
const keys = Object.keys(input);
const results = await func(Object.values(input));
return Object.fromEntries(keys.map((key, index) => [key, results[index]]));
};
var allObj = async (input) => {

@@ -481,4 +495,23 @@ return objectify(Promise.all, input);

};
// src/tools/ArrayUtils.ts
var ArrayUtils_exports = {};
__export(ArrayUtils_exports, {
randomise: () => randomise,
range: () => range,
reverse: () => reverse,
sortByMapped: () => sortByMapped,
zip: () => zip
});
var range = (length = 1) => new Array(length).fill(1).map((v, i) => i);
var zip = (...arrs) => {
const length = Math.min(...arrs.map((arr) => (arr || []).length));
return range(length).map((i) => arrs.map((arr) => (arr || [])[i]));
};
var sortByMapped = (arr, mapFn, sortFn = (a, b) => Number(a) - Number(b)) => zip(arr, arr.map(mapFn)).sort((a, b) => sortFn(a[1], b[1])).map(([v]) => v);
var randomise = (arr) => sortByMapped(arr, () => Math.random());
var reverse = (arr) => [...arr].reverse();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ArrayUtils,
CENTURY,

@@ -496,5 +529,11 @@ DAY,

YEAR,
all,
allLimit,
allLimitObj,
allObj,
centuries,
days,
decades,
each,
eachLimit,
getDeferred,

@@ -505,2 +544,4 @@ getProgressBar,

interval,
map,
mapLimit,
millenniums,

@@ -512,3 +553,7 @@ milliseconds,

progressBar,
randomise,
range,
reverse,
seconds,
sortByMapped,
stopInterval,

@@ -523,3 +568,4 @@ timer,

weeks,
years
years,
zip
});

2

package.json
{
"name": "swiss-ak",
"version": "1.4.0",
"version": "1.5.0",
"author": "Jack Cannon <jackc@annon.co.uk> (http://c.annon.co.uk/)",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -152,2 +152,70 @@ # swiss-ak (Swiss Army Knife)

## ArrayUtils
### range
Returns an array of the given length, where each value is equal to it's index
e.g. [0, 1, 2, ..., length]
```typescript
range(3); // [0, 1, 2]
range(5); // [0, 1, 2, 3, 4]
range(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
### zip
Converts multiple arrays into an array of 'tuples' for each value at the corresponding indexes.
Limited to the length of the shortest provided array
Inspired by python's 'zip'
> Note: The typing of this is messy - needs improvement
```typescript
zip([1, 2, 3, 4], ['a', 'b', 'c']); // [ [1, 'a'], [2, 'b'], [3, 'c'] ]
```
### sortByMapped
Sort an array by a mapped form of the values, but returning the initial values
```typescript
sortByMapped(['2p', '3p', '1p'], (v) => Number(v.replace('p', ''))); // ['1p', '2p', '3p']
sortByMapped(
['2p', '3p', '1p'],
(v) => Number(v.replace('p', '')),
(a, b) => b - a
); // ['3p', '2p', '1p']
```
### randomise
Returns a clone of the provided array with it's items in a random order
```typescript
randomise([1, 2, 3, 4, 5, 6]); // [ 5, 3, 4, 1, 2, 6 ]
randomise([1, 2, 3, 4, 5, 6]); // [ 5, 1, 3, 2, 4, 6 ]
randomise([1, 2, 3, 4, 5, 6]); // [ 6, 1, 4, 5, 2, 3 ]
randomise([1, 2, 3, 4, 5, 6]); // [ 1, 4, 5, 2, 3, 6 ]
randomise([1, 2, 3, 4, 5, 6]); // [ 2, 6, 1, 3, 4, 5 ]
```
### reverse
Returns a new array with the order reversed without affecting original array
```typescript
const arr1 = [1, 2, 3];
arr1; // [1, 2, 3]
arr1.reverse(); // [3, 2, 1]
arr1; // [3, 2, 1]
const arr2 = [1, 2, 3];
arr2; // [1, 2, 3]
reverse(arr2); // [3, 2, 1]
arr2; // [1, 2, 3]
```
## PromiseUtils

@@ -154,0 +222,0 @@

@@ -7,2 +7,3 @@ export * from './tools/types';

export * from './tools/PromiseUtils';
export * from './tools/ArrayUtils';

@@ -12,3 +13,4 @@ import * as times from './tools/times';

import * as progressBar from './tools/progressBar';
import * as ArrayUtils from './tools/ArrayUtils';
export { times, waiters, progressBar };
export { times, waiters, progressBar, ArrayUtils };

@@ -49,3 +49,3 @@ export interface DeferredPromise<T> {

*/
const all = async <T extends unknown>(promises: Promise<T>[]): Promise<any> => {
export const all = async <T extends unknown>(promises: Promise<T>[]): Promise<any> => {
await Promise.all(promises);

@@ -90,3 +90,3 @@ };

*/
const allLimit = <T extends unknown>(limit: number, items: ((index: number) => Promise<T>)[], noThrow: boolean = false): Promise<T[]> => {
export const allLimit = <T extends unknown>(limit: number, items: ((index: number) => Promise<T>)[], noThrow: boolean = false): Promise<T[]> => {
let runningCount: number = 0;

@@ -131,8 +131,2 @@ let errors: any[] = [];

const objectify = async (func: Function, input: any) => {
const keys = Object.keys(input);
const results = await func(Object.values(input));
return Object.fromEntries(keys.map((key, index) => [key, results[index]]));
};
/**

@@ -153,3 +147,3 @@ * Run an async function against each item in an array

*/
const each = async <Ti extends unknown>(items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<any>): Promise<any> => {
export const each = async <Ti extends unknown>(items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<any>): Promise<any> => {
await Promise.all(items.map((item: Ti, index: number, array: Ti[]) => func(item, index, array)));

@@ -175,3 +169,3 @@ };

*/
const eachLimit = async <Ti extends unknown>(
export const eachLimit = async <Ti extends unknown>(
limit: number,

@@ -203,3 +197,3 @@ items: Ti[],

*/
const map = async <Ti extends unknown, To extends unknown>(
export const map = async <Ti extends unknown, To extends unknown>(
items: Ti[],

@@ -238,3 +232,3 @@ func: (item?: Ti, index?: number, array?: Ti[]) => Promise<To>

*/
const mapLimit = async <Ti extends unknown, To extends unknown>(
export const mapLimit = async <Ti extends unknown, To extends unknown>(
limit: number,

@@ -252,2 +246,8 @@ items: Ti[],

const objectify = async (func: Function, input: any) => {
const keys = Object.keys(input);
const results = await func(Object.values(input));
return Object.fromEntries(keys.map((key, index) => [key, results[index]]));
};
/**

@@ -285,3 +285,3 @@ * Like Promise.all, but pass/receive objects rather than arrays

*/
const allObj = async <T extends unknown>(input: { [key: string]: Promise<T> }): Promise<{ [key: string]: T }> => {
export const allObj = async <T extends unknown>(input: { [key: string]: Promise<T> }): Promise<{ [key: string]: T }> => {
return objectify(Promise.all, input);

@@ -326,3 +326,3 @@ };

*/
const allLimitObj = async <T extends unknown>(
export const allLimitObj = async <T extends unknown>(
limit: number,

@@ -329,0 +329,0 @@ input: { [key: string]: (index: number) => Promise<T> },

@@ -38,3 +38,3 @@ import { ms, SECOND } from './times';

export type CustomEntryDict<T, TName> = {
[K in keyof T]: (durations: TimerDurations<TName>) => number;
[K in keyof T]?: (durations: TimerDurations<TName>) => number;
};

@@ -173,3 +173,3 @@

} else {
cEntries = Object.entries(customEntries).map(([label, func]) => ({ label, duration: func(durations) }));
cEntries = Object.entries(customEntries).map(([label, func]) => ({ label, duration: (func || (() => 0))(durations) || 0 }));
}

@@ -176,0 +176,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc