Add arrayUnzip (#1598)

This commit is contained in:
Jaco
2022-07-16 11:54:02 +03:00
committed by GitHub
parent b4b80bbf67
commit 0e55357053
8 changed files with 60 additions and 23 deletions
+1
View File
@@ -10,4 +10,5 @@ export { arrayFilter } from './filter';
export { arrayFlatten } from './flatten';
export { arrayRange } from './range';
export { arrayShuffle } from './shuffle';
export { arrayUnzip } from './unzip';
export { arrayZip } from './zip';
+1 -1
View File
@@ -5,7 +5,7 @@
* @name arrayShuffle
* @description Shuffles the input array (unlike sort, this is not done in-place)
*/
export function arrayShuffle <T> (input: T[]): T[] {
export function arrayShuffle <T> (input: readonly T[]): T[] {
const result = input.slice();
let curr = result.length;
+12
View File
@@ -0,0 +1,12 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { arrayUnzip } from '.';
describe('arrayUnzip', (): void => {
it('unzips entries', (): void => {
expect(
arrayUnzip([['a', 1], ['b', 2], ['c', 3]])
).toEqual([['a', 'b', 'c'], [1, 2, 3]]);
});
});
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
/**
* @name arrayUnzip
* @description Splits a single [K, V][] into [K[], V[]]
*/
export function arrayUnzip <K, V> (entries: readonly [K, V][]): [K[], V[]] {
const keys = new Array<K>(entries.length);
const values = new Array<V>(entries.length);
for (let i = 0; i < entries.length; i++) {
[keys[i], values[i]] = entries[i];
}
return [keys, values];
}
+5 -5
View File
@@ -12,11 +12,11 @@ export { packageInfo } from './packageInfo';
const importFetch = import('node-fetch').catch(() => null);
// keep track of the resolved import value
let resolvedFetch: typeof fetch | null = null;
let modFn: typeof fetch | null = null;
async function nodeFetch (...args: Parameters<typeof fetch>): Promise<Response> {
if (resolvedFetch) {
return resolvedFetch(...args);
if (modFn) {
return modFn(...args);
}
const mod = await importFetch;
@@ -25,9 +25,9 @@ async function nodeFetch (...args: Parameters<typeof fetch>): Promise<Response>
throw new Error('Unable to import node-fetch in this environment');
}
resolvedFetch = mod.default as unknown as typeof fetch;
modFn = mod.default as unknown as typeof fetch;
return resolvedFetch(...args);
return modFn(...args);
}
export const fetch = extractGlobal('fetch', nodeFetch);