Skip to content

Instantly share code, notes, and snippets.

@jjhiggz
Created August 11, 2023 13:24
Show Gist options
  • Save jjhiggz/c496025650d949813d1f47427c5206b6 to your computer and use it in GitHub Desktop.
Save jjhiggz/c496025650d949813d1f47427c5206b6 to your computer and use it in GitHub Desktop.
Why Record Types can be annoying in JS / TS
// let's say I want to find the most occurring year here
const years = [1999,1993, 1992, 1991, 1991, 1999, 1993, 1993]
// I can use a Record<number, number> to create a map like so
// {1999: 2, 1993: 3, 1992: 1, 1991: 2, }
const yearMap: Record<number, number> = {}
for(let year of years){
if(year in yearMap){
yearMap[year] += 1
} else {
yearMap[year] = 1
}
}
// Now if I want to iterate over the object to find find the max occurring year
// All the conversions turn the keys into strings
console.log(Object.keys(yearMap)) // ["1991", "1992", "1993", "1999"] instead of [1991, 1992, 1993, 1999]
// Just to solve the problem for funziesm, feel free to ignore
const entries = Object.entries(yearMap)
let maxEntry = entries[0] || null
for(let currEntry of Object.entries(yearMap)){
if(!currEntry || currEntry[1] > maxEntry[1]){
maxEntry = currEntry
continue
}
}
console.log(maxEntry[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment