1 import TaxReturn from './TaxReturn';
2 import Form, { FormClass } from './Form';
4 export abstract class Line<T> {
5 private _description?: string;
7 _id: string; // _id is set by Form.init().
8 form: Form<any, any>; // Set by Form.init();
10 constructor(description?: string) {
11 this._description = description;
18 get description(): string {
19 return this._description;
22 abstract value(tr: TaxReturn): T;
25 type ComputeFunc<T> = (tr: TaxReturn) => T;
27 export class ComputedLine<T> extends Line<T> {
28 private _compute: ComputeFunc<T>;
30 constructor(compute: ComputeFunc<T>, description?: string) {
32 this._compute = compute;
35 value(tr: TaxReturn): T {
36 return this._compute(tr);
40 export class ReferenceLine<F extends Form<any>,
41 L extends keyof F['lines'],
42 T extends ReturnType<F['lines'][L]['value']>>
44 private _form: FormClass<F>;
46 private _fallback?: T;
48 // If creating a ReferenceLine and F is the same class as the
49 // the one the Line is in, erase |form|'s type with |as any| to
50 // keep TypeScript happy.
51 constructor(form: FormClass<F>, line: L, description?: string, fallback?: T) {
52 super(description || `Reference F${form}.L${line}`);
55 this._fallback = fallback;
58 value(tr: TaxReturn): T {
59 const form: F = tr.findForm(this._form);
60 if (this._fallback !== undefined && !form)
61 return this._fallback;
62 const value: T = form.getValue(tr, this._line);
67 export class InputLine<U = unknown, T extends keyof U = any> extends Line<U[T]> {
72 constructor(input: T, description?: string) {
73 super(description || `Input from ${input}`);
77 value(tr: TaxReturn): U[T] {
78 return this.form.getInput<T>(this._input);
82 export class AccumulatorLine<F extends Form<any>,
83 L extends keyof F['lines']>
84 extends Line<number> {
85 private _form: FormClass<F>;
88 constructor(form: FormClass<F>, line: L, description?: string) {
89 super(description || `Accumulator F${form}.L${line}`);
95 const forms: F[] = tr.findForms(this._form);
96 return sumLineOfForms(tr, forms, this._line);
100 export function sumLineOfForms<F extends Form<any>, L extends keyof F['lines']>(
101 tr: TaxReturn, forms: F[], line: L): number {
102 const reducer = (acc: number, curr: F) => acc + curr.getValue(tr, line);
103 return forms.reduce(reducer, 0);