/
index.ts
37 lines (27 loc) · 1.64 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Function, Dimension, Cube, criteria, pivot, aggregate, average, Matrix } from '..';
import { Player, squad } from './fulham';
import { distinct } from './distinct';
// the position dimension we want in a custom order
const positions: string[] = ['Goalkeeper', 'Defender', 'Midfielder', 'Forward'];
// the countries dimension we derive from the squad data and order alphabetically
const countries: string[] = squad.map(player => player.country).filter(distinct).sort();
// we then create dimensions which also reference a property in the source data
const x: Dimension<Player> = positions.map(criteria('position'));
const y: Dimension<Player> = countries.map(criteria('country'));
// create the pivot cube from the squad data using position and country for x and y axes
const cube: Cube<Player> = pivot(squad, y, x);
// find the average age of players by position by country as at 2021-05-23
const result: Matrix<number> = aggregate(cube, average(age(new Date('2021-05-23'))));
// Creates a callback to calculate a players age from their date of birth as at a given date
function age(asAt: Date = new Date()): Function<Player, number> {
return player => new Date(asAt.getTime() - player.dateOfBirth.getTime()).getUTCFullYear() - 1970;
}
// pretty print the result with axes
console.log(`\t${positions.map(print).join('\t')}`);
console.log(result.map((row, index) => [countries[index], ...row].map(print).join('\t')).join('\n'));
//console.log(partition(squad, x));
// Print a value in 7 characters and truncate with ellipsis
function print(value: any) {
const str = String(value || '');
return str.length < 8 ? str : (str.substring(0, 6) + '\u2026');
}