Skip to content

Instantly share code, notes, and snippets.

@Avi-E-Koenig
Created December 9, 2021 11:41
Show Gist options
  • Save Avi-E-Koenig/628ecad90bf6b884a7eb8dd0b0cb4e24 to your computer and use it in GitHub Desktop.
Save Avi-E-Koenig/628ecad90bf6b884a7eb8dd0b0cb4e24 to your computer and use it in GitHub Desktop.
quick user db as mapped key->val collection
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