Skip to content

Instantly share code, notes, and snippets.

@pirey
Created December 28, 2023 11:05
Show Gist options
  • Save pirey/251afdfb375a3a7509492b98c6adec31 to your computer and use it in GitHub Desktop.
Save pirey/251afdfb375a3a7509492b98c6adec31 to your computer and use it in GitHub Desktop.
some helper functions
function randomBoolean() {
return Math.random() < 0.5;
}
function chunkArray<T>(array: T[], chunkSize: number): T[][] {
return Array.from(
{ length: Math.ceil(array.length / chunkSize) },
(_, index) => array.slice(index * chunkSize, (index + 1) * chunkSize),
);
}
async function simulateHttpRequest<T>(payload: T): Promise<T> {
// return dummyPromise()
// .then(() => fetch("https://jsonplaceholder.typicode.com/posts"))
// .then((res) => res.json())
// .then(() => payload);
return fetch("https://jsonplaceholder.typicode.com/posts")
.then((res) => res.json())
.then(() => payload);
}
function bytes2MB(bytes: number): number {
return bytes / (1024 * 1024);
}
async function dummyPromise(dur: number = -1) {
const maxSeconds = 3;
const defaultDur = Math.random() * 1000 * maxSeconds;
return new Promise((resolve, reject) => {
setTimeout(
() => {
if (randomBoolean()) {
resolve(undefined);
} else {
reject("some reason");
}
},
dur < 0 ? defaultDur : dur,
);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment