Code coverage report for node_acl/lib/contract.js

Statements: 72.55% (37 / 51)      Branches: 71.43% (10 / 14)      Functions: 75% (6 / 8)      Lines: 72.55% (37 / 51)      Ignored: none     

All files » node_acl/lib/ » contract.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105                                  1   1 564   1   1 1651 1651 1651 1651 1651           1 1738 1738 1738 1651   87 87     1             1 1954     1 1738 1738 87   1651 1954 1954       1954 1954 1954 2116 1954 1954     1954       1651       1                                     1    
/**
  Design by Contract module (c) OptimalBits 2011.
 
  Roadmap:
    - Optional parameters. ['(string)', 'array']
    - Variable number of parameters.['number','...']
 
  api?:
  
  contract(arguments)
    .params('string', 'array', '...')
    .params('number')
    .end()
  
*/
"use strict";
 
var noop = {};
 
noop.params = function(){
  return this;
};
noop.end = function(){};
 
var contract = function(args){
  Eif(contract.debug===true){
    contract.fulfilled = false;
    contract.args = args;
    contract.checkedParams = [];
    return contract;
  }else{
    return noop;
  }
};
 
contract.params = function(){
  var i, len;
  this.fulfilled |= checkParams(this.args, arguments);
  if(this.fulfilled){
    return noop;
  }else{
    this.checkedParams.push(arguments);
    return this;
  }
}
contract.end = function(){
  if(!this.fulfilled){
    printParamsError(this.args, this.checkedParams);
    throw new Error('Broke parameter contract');
  }
}
 
var typeOf = function(obj){
  return Array.isArray(obj)?'array':typeof obj;
};
 
var checkParams = function(args, contract){
  var fulfilled, types, type, i, j, len;
  if(args.length !== contract.length){
    return false;
  }else{
    for(i=0, len=args.length;i<len;i++){
      try{
        types = contract[i].split('|');
      }catch(e){
        console.log(args)
      }
      type = typeOf(args[i]);
      fulfilled = false;
      for(j=0, len=types.length;j<len;j++){
        if (type === types[j]){
          fulfilled = true;
          break;
        }
      }
      Iif(fulfilled===false){
        return false;
      }
    }
    return true;
  }
};
 
var printParamsError = function(args, checkedParams){
  var msg = 'Parameter mismatch.\nInput:\n( ',
      type,
      input,
      i;
  for(input in args){
    type = typeOf(args[input]);
    msg += args[input] + '{'+type+'} ';
  }
  
  msg += ')\nAccepted:\n';
  
  for (i=0; i<checkedParams.length;i++){
    msg += '('+ checkedParams[i] + ')\n';
  }
 
  console.log(msg);
};
 
exports = module.exports = contract;