type_conversion.js (1583B)
1 var typed = require('../typed-function'); 2 3 // define type conversions that we want to support order is important. 4 // There is also an utility function typed.addConversion(conversion) for this. 5 typed.conversions = [ 6 { 7 from: 'boolean', 8 to: 'number', 9 convert: function (x) { 10 return +x; 11 } 12 }, 13 { 14 from: 'boolean', 15 to: 'string', 16 convert: function (x) { 17 return x + ''; 18 } 19 }, 20 { 21 from: 'number', 22 to: 'string', 23 convert: function (x) { 24 return x + ''; 25 } 26 } 27 ]; 28 29 // create a typed function with multiple signatures 30 // 31 // where possible, the created function will automatically convert booleans to 32 // numbers or strings, and convert numbers to strings. 33 // 34 // note that the length property is only available on strings, and the toFixed 35 // function only on numbers, so this requires the right type of argument else 36 // the function will throw an exception. 37 var fn = typed({ 38 'string': function (name) { 39 return 'Name: ' + name + ', length: ' + name.length; 40 }, 41 'string, number': function (name, value) { 42 return 'Name: ' + name + ', length: ' + name.length + ', value: ' + value.toFixed(3); 43 } 44 }); 45 46 // use the function the regular way 47 console.log(fn('foo')); // outputs 'Name: foo, length: 3' 48 console.log(fn('foo', 2/3)); // outputs 'Name: foo, length: 3, value: 0.667' 49 50 // calling the function with non-supported but convertible types 51 // will work just fine: 52 console.log(fn(false)); // outputs 'Name: false, length: 5' 53 console.log(fn('foo', true)); // outputs 'Name: foo, length: 3, value: 1.000'