Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- In typescript, we can create interface function which defined the parameters
- and return type. The snippet is below.
- ```
- interface SearchFunc() {
- (...keywords?: string[]): PageRank
- }
- ```
- The _SearhFunc_ interface defines that a search function should accept bunch of
- keywords and return the result in PageRank format.
- Now we can define a search engine, that accept search query, and search function
- should be injected during engine construction.
- ```
- class SearchEngine() {
- storage: PageStorage;
- searchFunc: SearchFunc;
- constructor(func: SearchFunc) {
- this.searchFunc = func;
- }
- query(keywords: string[]): PageRank {
- // ... internal process
- return searchFunc(keywords);
- }
- }
- ```
- Let's take another problem, say we want to make income tax calculator that have
- two main functions:
- 1. tax calculcation based on income
- 2. tax exemption based on which band
- As we are unit test follower, we should define breaking unit test (in jest)
- first and then implement it with name _pph21_.
- ```
- describe('tax calculation function', () => {
- const {calc} = require('./pph21');
- it('should calculate the tax based on bracket regulation', () => {
- const monthlyIncome = 3500;
- const tax = 55;
- expect(
- calc(12 * monthlyIncome)
- ).toBe(tax);
- })
- // .. other scenarios
- })
- // implementation
- interface CalcFunc {
- (taxableIncome: number): number;
- }
- const pph21: CalcFunc = function (income): number {
- let tax = 0;
- // ... internal process
- return tax;
- }
- ```
- Next we may see how the _ExemptFunc_ written in red-green approach.
- ```
- describe('income exemption function', () => {
- const {exempt} = require('./pph21');
- it('should return exemption number based on band', () => {
- const band = 'K0';
- const exemption = 50;
- expect(
- exempt(band)
- ).toBe(exemption);
- })
- // ... other scenarios
- })
- // implementation
- interface ExemptFunc {
- (band: string): number;
- }
- const exemptPPH21: ExemptFunc = function(band): number {
- let exemption = 0;
- // ... internal process
- return exemption;
- }
- ```
- Nice, to conclude the whole gist I would like to write the _TaxEngine_ with
- injected _CalcFunc_ and _ExemptFunc_.
- ```
- class TaxEngine {
- calc: CalcFunc;
- exempt: ExemptFunc;
- constructor(calc: CalcFunc, exempt: ExemptFunc) {
- this.calc = calc;
- this.exempt = exempt;
- }
- }
- const {pph21, exemptPPH21} = require('./pph21');
- const pph21Engine = new TaxEngine(pph21, exemptPPH21);
- ```
- Interested for more? please do contact me.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement