Created
December 9, 2021 11:41
-
-
Save Avi-E-Koenig/628ecad90bf6b884a7eb8dd0b0cb4e24 to your computer and use it in GitHub Desktop.
quick user db as mapped key->val collection
This file contains hidden or 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
const arrayMapper = (array, uniqueID) => array.reduce((acc, obj, index) => { | |
if (!obj?.[uniqueID]) { | |
console.error("π ~ file: doodle.js ~ line 6 ~ arrayMapper ~ ", { obj, uniqueID, index }) | |
throw new Error('uniqueId no found') | |
} | |
acc[obj[uniqueID]] = obj | |
return acc; | |
}, {}) | |
function uuidv4() { | |
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => | |
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) | |
); | |
} | |
async function fetchUsers() { | |
try { | |
const response = await fetch('https://randomuser.me/api/?results=50') | |
const students = await response.json() | |
return [students, null] | |
} catch (error) { | |
console.log("π ~ file: doodle.js ~ line 25 ~ fetchUsers ~ error", error) | |
return [null, error] | |
} | |
} | |
async function main() { | |
try { | |
const [response, error] = await fetchUsers(); | |
if (error) throw error | |
const users = response.results; | |
const uuidArr = [] | |
function setUserId(user) { | |
const uuid = uuidv4() | |
if (uuidArr.includes(uuid)) { | |
setUserId(user) | |
} | |
uuidArr.push(uuid) | |
user._id = uuid; | |
return user; | |
} | |
users.forEach(setUserId) | |
console.log("π ~ file: doodle.js ~ line 52 ~ main ~ users", arrayMapper(users, '_id')) | |
} catch (err) { | |
console.log("π ~ file: doodle.js ~ line 33 ~ main ~ error", err) | |
} | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment