Id functor Typescript -example

by dimitrs_papadimitriou

HTML

<code>
   new Id(2).map(square).Value : <span id="1"  ></span>
 </code>

<br>
  <code> 
  new Id(square(2))  :  <span id="2"  ></span>
 </code>

TypeScript

function log(id:number,x:any):void {
     $("#"+id.toString()).text(x);
  }  
  

abstract class AbstractObject<T> {
  abstract Display(format: (v: T) => string): string;
}

class RealObject<T> extends AbstractObject<T> {
  Display(format: (v: T) => string): string {
    return format(this.Value);
  }

  Value: T;
  constructor(value: T) {
    super();
    this.Value = value;
  }
}

class NullObject<T> extends AbstractObject<T> {
  Display(format: (v: T) => string): string {
    return "no client found";
  }
}

class Client {
  Id: number;
  Name: string;
  constructor(id: number, name: string) {
    this.Id = id;
    this.Name = name;
  }

}

class MockClientRepository {
  GetById(id: number): AbstractObject<Client> {
    let clients: Array<Client> = [new Client(1, "jim"), new Client(2, "john")];

    var client = clients.find(c => c.Id == id);

    if (!client) return new NullObject<Client>();
    else return new RealObject<Client>(client);
  }
}

var d = new MockClientRepository().GetById(1).Display(v => v.Name);
 log( 1,d)