Created
August 31, 2024 04:30
-
-
Save jjhiggz/109eff5bc9279356dbdcaa722cb4341d to your computer and use it in GitHub Desktop.
createDictionary.ts
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 getCounts = <T,>( | |
input: Iterable<T>, | |
shouldCountCb: (input: T) => unknown, | |
serializeKey: (input: T) => any = input => input, | |
) => { | |
let counts = {} as Record<any, number> | |
for(let val of input){ | |
if(shouldCountCb(val)){ | |
counts[serializeKey(val)] = (counts[serializeKey(val)] ?? 0) + 1 | |
} | |
} | |
return counts | |
} | |
const isVowel = ( | |
input: string, includeY: boolean = false | |
) => [...["a", "e", "i", "o", "u"], ...(includeY ? ["y"] : [])] | |
.includes(input.toLowerCase()) | |
console.log(getCounts("hello", isVowel )) | |
console.log(getCounts(["h", "e", "l", "l", "o", ], isVowel)) | |
const people = [ | |
{name: 'jon', age: 10}, | |
{name: 'jonn', age: 20}, | |
{name: 'jonnn', age: 21}, | |
{name: 'jonnnn', age: 20}, | |
{name: 'jonnnnn', age: 21}, | |
{name: 'jonnnnn', age: 23}, | |
{name: 'jonnnnnnn', age: 32}, | |
{name: 'jon', age: 10}, | |
] | |
const peopleBetween20And30Counts = getCounts( | |
people, | |
person => person.age >= 20 && person.age <= 30, | |
person => person.age, | |
) | |
console.log(peopleBetween20And30Counts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment