mirror of https://github.com/waku-org/js-waku.git
chore: move `random_subset.ts` to `@waku/utils` (#1191)
This commit is contained in:
parent
604ba1a889
commit
6b87ca1c4d
|
@ -1,4 +1,4 @@
|
||||||
import { getPseudoRandomSubset } from "./random_subset.js";
|
import { getPseudoRandomSubset } from "@waku/utils";
|
||||||
|
|
||||||
export const DefaultWantedNumber = 1;
|
export const DefaultWantedNumber = 1;
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
|
import { getPseudoRandomSubset } from "@waku/utils";
|
||||||
import { expect } from "chai";
|
import { expect } from "chai";
|
||||||
|
|
||||||
import { getPseudoRandomSubset } from "./random_subset.js";
|
|
||||||
|
|
||||||
describe("Discovery", () => {
|
describe("Discovery", () => {
|
||||||
it("returns all values when wanted number matches available values", function () {
|
it("returns all values when wanted number matches available values", function () {
|
||||||
const values = ["a", "b", "c"];
|
const values = ["a", "b", "c"];
|
||||||
|
|
|
@ -1,30 +0,0 @@
|
||||||
/**
|
|
||||||
* Return pseudo random subset of the input.
|
|
||||||
*/
|
|
||||||
export function getPseudoRandomSubset<T>(
|
|
||||||
values: T[],
|
|
||||||
wantedNumber: number
|
|
||||||
): T[] {
|
|
||||||
if (values.length <= wantedNumber || values.length <= 1) {
|
|
||||||
return values;
|
|
||||||
}
|
|
||||||
|
|
||||||
return shuffle(values).slice(0, wantedNumber);
|
|
||||||
}
|
|
||||||
|
|
||||||
function shuffle<T>(arr: T[]): T[] {
|
|
||||||
if (arr.length <= 1) {
|
|
||||||
return arr;
|
|
||||||
}
|
|
||||||
const randInt = (): number => {
|
|
||||||
return Math.floor(Math.random() * Math.floor(arr.length));
|
|
||||||
};
|
|
||||||
|
|
||||||
for (let i = 0; i < arr.length; i++) {
|
|
||||||
const j = randInt();
|
|
||||||
const tmp = arr[i];
|
|
||||||
arr[i] = arr[j];
|
|
||||||
arr[j] = tmp;
|
|
||||||
}
|
|
||||||
return arr;
|
|
||||||
}
|
|
|
@ -0,0 +1 @@
|
||||||
|
export * from "./random_subset.js";
|
|
@ -1,2 +1,3 @@
|
||||||
export * from "./bytes/index.js";
|
export * from "./bytes/index.js";
|
||||||
export * from "./libp2p/index.js";
|
export * from "./libp2p/index.js";
|
||||||
|
export * from "./common/index.js";
|
||||||
|
|
Loading…
Reference in New Issue