Last active
April 12, 2019 18:04
-
-
Save NickStrupat/f148c69c9531b1c05208ec2ee00f1358 to your computer and use it in GitHub Desktop.
Grouping using maps example (now with es5)
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
class Person { | |
name!: string; | |
age!: number; | |
sex!: string; | |
public toString = () : string => JSON.stringify(this); | |
} | |
const people: Person[] = [ | |
{ age: 25, sex: 'f', name: 'Sue' }, | |
{ age: 30, sex: 'f', name: 'Angela' }, | |
{ age: 30, sex: 'm', name: 'Joe' }, | |
{ age: 30, sex: 'm', name: 'Frank' }, | |
{ age: 35, sex: 'f', name: 'Sarah' } | |
]; | |
type AgeGrouping = Map<number, SexGrouping>; | |
type SexGrouping = Map<string, Array<Person>>; | |
function getSexGrouping(map: AgeGrouping, age: number): SexGrouping { | |
let sexGrouping = map.get(age); | |
if (sexGrouping === undefined) | |
map.set(age, sexGrouping = new Map<string, Array<Person>>()); | |
return sexGrouping; | |
} | |
function getPeople(map: SexGrouping, sex: string): Array<Person> { | |
let people = map.get(sex); | |
if (people === undefined) | |
map.set(sex, people = new Array<Person>()); | |
return people; | |
} | |
const ageGrouping = new Map<number, SexGrouping>(); | |
for (let person of people) { | |
const sexGrouping = getSexGrouping(ageGrouping, person.age); | |
const people = getPeople(sexGrouping, person.sex); | |
people.push(person); | |
} | |
console.log(ageGrouping); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment