SoFunction
Updated on 2025-04-06

JavaScript mock train ticket booking and refund example


if(jQuery){}else{
 //
}

function Server(){
 var self = this;

  = [];

 self._init= function(number){
  if(typeof(number) != 'number')
   throw ('type error');
  for(i=0;i<number;i++){
   (new Ticket());
  }
 };

//Direction whether a ticket can be bought, and it can be achieved through the AND or operation.
//For example: Order o is Beijing-Jinan (001111111), and a certain ticket is (0000000011) (sold Beijing-Nanjing), then return false
//For example: Order o is Beijing-Jinan (0011111111), and a certain ticket is (1111100011) (Sold in Xuzhou-Nanjing), then return true
  = function(o,t){
  var _o = ''
  for(j=0; j<; j++){
   _o += o[j]=='0'?1:0;
  }
  var r1 = (parseInt(,2) | parseInt(o,2)) & parseInt(_o,2);
  var r2 = parseInt(_o,2);
  return r1 == r2;
 };

//Sell a ticket
 self.pop1Ticket = function(o){
   for(i=0;i < ;i++){
    if((o,[i])){
     ([i],o);
     return i;
   }
  };
  return -1;
 };

//Implementation of selling tickets, changing the binary string, such as '11111111'->'00111111';
  = function(t,o){
   = (parseInt(,2) & parseInt(o,2)).toString(2);
  //alert();

 };

//Inquiry of remaining tickets
  = function(o){
   var count=0;
   for(i=0;i < ;i++){
    count += (o,[i])?1:0;
  };
  return count;
 }

//Refund, or operation
  = function(o){
   for(i=0;i < ;i++){
    if(!(o,[i])){
     var _o = ''
     for(j=0; j<; j++){
      _o += o[j]=='0'?1:0;
     }
     [i].tic = (parseInt([i].tic,2) | parseInt(_o,2)).toString(2);
     return i;
   } 
  };

  return -1;
 }
}

//Data Model: Tickets
function Ticket(){
 var self = this;
//The ticket is the beginning of the ticket
  = '1111111111';
}

//Data Model: Order
function Order(from, to){
 var self = this;
 var s = '';
 for(i=0;i<10;i++){
  s += (i>=from && i<to)?0:1;
 }
 return s;
}

//12306 Backstage
Server = new Server();
//Initial status, the ticket pool has 400 full tickets
Server._init(400);