Files
2025-05-04 14:57:42 +02:00

36 lines
1.4 KiB
TypeScript

const DEFAULT_STUDENTS = [ 'Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry' ]
const PLANT_CODES = { G: 'grass', V: 'violets', R: 'radishes', C: 'clover', } as const
type Student = string
type PlantCode = keyof (typeof PLANT_CODES)
type Plant = (typeof PLANT_CODES)[PlantCode]
type Spot = Plant | null
type SpotsPerStudent = Record<Student, [Spot, Spot, Spot, Spot]>
const isPlantCode = (code: string): code is PlantCode => PLANT_CODES.hasOwnProperty(code)
export class Garden {
private _state: SpotsPerStudent = {}
static parseDiagram(diagram: string, students: Student[] = DEFAULT_STUDENTS): SpotsPerStudent {
const result: SpotsPerStudent = {}
const rows = diagram.split('\n').map(row => row.split('').filter(isPlantCode).map(code => PLANT_CODES[code]))
if (rows.length !== 2) throw new Error('Expected 2 rows')
if (rows[0].length !== rows[1].length) throw new Error('Rows are not of equal length')
for (let i = 0; i < rows[0].length; i+=2) {
result[students[Math.floor(i/2)]] = [rows[0][i], rows[0][i+1], rows[1][i], rows[1][i+1]]
}
return result
}
constructor(_diagram: string, _students: Student[] = DEFAULT_STUDENTS) {
this._state = Garden.parseDiagram(_diagram, [..._students].sort())
}
public plants(student: Student): Plant[] {
return (this._state[student] || []).filter(spot => spot !== null)
}
}