Created
December 28, 2023 11:05
-
-
Save pirey/251afdfb375a3a7509492b98c6adec31 to your computer and use it in GitHub Desktop.
some helper functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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