All files / src/lib types.js

100% Statements 33/33
100% Branches 16/16
100% Functions 12/12
100% Lines 33/33
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  1x   1x                                   13x 13x       26x 2x   24x       27x 1x   26x       26x 26x     27x 27x       23x 1x     22x       10x 1x     9x 17x 1x     16x         17x 17x   1x     16x       56x 56x       23x 1x     22x       23x    
'use strict';
var _ = require('lodash');
 
module.exports = {
  seems: {
    Integer: seemsInteger,
    Float: seemsFloat,
    Boolean: seemsBoolean,
    String: seemsString,
    Array: seemsArray
  },
  convert: {
    Integer: createType('Integer', IntegerConverter),
    Float: createType('Float', FloatConverter),
    Boolean: createType('Boolean', BooleanConverter),
    String: createType('String', StringConverter),
    Array: ArrayConverter
  }
};
 
function createType(name, impl){
  impl._name = name;
  return impl;
}
 
function IntegerConverter(mixed) {
  if (!seemsInteger(mixed)) {
    throw new Error('`' + mixed + '` is not an integer, could not convert it.');
  }
  return parseInt(mixed, 10);
}
 
function FloatConverter(mixed) {
  if (!seemsFloat(mixed)) {
    throw new Error('`' + mixed + '` is not an float, could not convert it.');
  }
  return parseFloat(mixed);
}
 
function seemsInteger(mixed){
  var maybeInt = parseInt(mixed, 10);
  return !isNaN(maybeInt) && mixed + '' === maybeInt.toFixed(0);
}
function seemsFloat(mixed){
  var maybeFloat = parseFloat(mixed);
  return !isNaN(maybeFloat);
}
 
function BooleanConverter(mixed) {
  if (!seemsBoolean(mixed)) {
    throw new Error('`' + mixed + '` is not an boolean, could not convert it.');
  }
 
  return String(mixed).toLowerCase() === 'true';
}
 
function ArrayConverter(itemConverter){
  if(!_.isFunction(itemConverter)){
    throw new Error('itemConverter from ArrayConverter(itemConverter) should be a function');
  }
 
  return createType('Array('+itemConverter._name+')', function(mixed){
    if(!seemsArray(itemConverter, mixed)){
      throw new Error('`' + mixed + '` is not an Array('+itemConverter._name+'), could not convert it.');
    }
 
    return mixed.split(',').map(itemConverter);
  });
}
 
function seemsArray(itemConverter, itemType){
  try{
    itemType.split(',').every(itemConverter);
  } catch(err){
    return false;
  }
 
  return true;
}
 
function seemsBoolean(mixed) {
  var v = String(mixed).toLowerCase();
  return v === 'true' || v === 'false';
}
 
function StringConverter(mixed){
  if(!seemsString(mixed)){
    throw new Error('`' + mixed + '` is not an string, could not convert it.');
  }
 
  return mixed;
}
 
function seemsString(mixed){
  return _.isString(mixed);
}