1 // Copyright 2020 Blue Static <https://www.bluestatic.org>
2 // This program is free software licensed under the GNU General Public License,
3 // version 3.0. The full text of the license can be found in LICENSE.txt.
4 // SPDX-License-Identifier: GPL-3.0-only
6 import TaxReturn from './TaxReturn';
7 import Form, { FormClass } from './Form';
9 export abstract class Line<T> {
10 private _description?: string;
12 _id: string; // _id is set by Form.init().
13 form: Form<any, any>; // Set by Form.init();
15 constructor(description?: string) {
16 this._description = description;
23 get description(): string {
24 return this._description;
27 abstract value(tr: TaxReturn): T;
30 type ComputeFunc<T> = (tr: TaxReturn) => T;
32 export class ComputedLine<T> extends Line<T> {
33 private _compute: ComputeFunc<T>;
35 constructor(compute: ComputeFunc<T>, description?: string) {
37 this._compute = compute;
40 value(tr: TaxReturn): T {
41 return this._compute(tr);
45 export class ReferenceLine<F extends Form<any>,
46 L extends keyof F['lines'],
47 T extends ReturnType<F['lines'][L]['value']>>
49 private _form: FormClass<F>;
51 private _fallback?: T;
53 // If creating a ReferenceLine and F is the same class as the
54 // the one the Line is in, erase |form|'s type with |as any| to
55 // keep TypeScript happy.
56 constructor(form: FormClass<F>, line: L, description?: string, fallback?: T) {
57 super(description || `Reference F${form.name}.L${line}`);
60 this._fallback = fallback;
63 value(tr: TaxReturn): T {
64 const form: F = tr.findForm(this._form);
65 if (this._fallback !== undefined && !form)
66 return this._fallback;
67 const value: T = form.getValue(tr, this._line);
72 export class InputLine<U = unknown, T extends keyof U = any> extends Line<U[T]> {
74 private _fallback: U[T];
78 constructor(input: T, description?: string, fallback?: U[T]) {
79 super(description || `Input from ${input}`);
81 this._fallback = fallback;
84 value(tr: TaxReturn): U[T] {
85 if (!this.form.hasInput(this._input) && this._fallback !== undefined)
86 return this._fallback;
87 return this.form.getInput<T>(this._input);
91 export class AccumulatorLine<F extends Form<any>,
92 L extends keyof F['lines']>
93 extends Line<number> {
94 private _form: FormClass<F>;
97 constructor(form: FormClass<F>, line: L, description?: string) {
98 super(description || `Accumulator F${form}.L${line}`);
104 const forms: F[] = tr.findForms(this._form);
105 return sumLineOfForms(tr, forms, this._line);
109 export function sumLineOfForms<F extends Form<any>, L extends keyof F['lines']>(
110 tr: TaxReturn, forms: F[], line: L): number {
111 const reducer = (acc: number, curr: F) => acc + curr.getValue(tr, line);
112 return forms.reduce(reducer, 0);