Skip to content

Instantly share code, notes, and snippets.

@rawnly
Last active March 13, 2018 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rawnly/ca3d9d18b174b6f3e8eec6a807c530b5 to your computer and use it in GitHub Desktop.
Save rawnly/ca3d9d18b174b6f3e8eec6a807c530b5 to your computer and use it in GitHub Desktop.
Javascript TypeCheck
module.exports = function typeCheck(...args) {
args.map(({
param,
expected
}) => {
var type = Array.isArray(param) ? 'array' : typeof param;
if (Array.isArray(expected)) {
if (expected.indexOf(type) < 0) {
throw new SyntaxError(`Expected ${expected.join( expected.length > 1 ? ' or ' : '')} saw ${type}`);
}
return;
} else {
if (expected !== type) {
throw new SyntaxError(`Expected ${expected} saw ${type}`)
}
return;
}
})
return;
}
interface Argument {
param: any,
expected: String[] | String
}
export default function typeCheck(...args: Argument[]): void {
args.map(({param, expected}) => {
var type = Array.isArray(param) ? 'array' : typeof param;
if ( Array.isArray(expected) ) {
if ( expected.indexOf(type) < 0 ) {
throw new SyntaxError(`Expected ${expected.join( expected.length > 1 ? ' or ' : '')} saw ${type}`);
}
return;
} else {
if ( expected !== type ) {
throw new SyntaxError(`Expected ${expected} saw ${type}`)
}
return;
}
})
return;
}

Usage

Use it like:

  import typeCheck from './typeCheck';

  /**
   * @name round
   * @description Write a function that round a number (`n`) to given decimal places.
   *
   * 
   * @example Usage:
   * round(Math.PI, 2) // => 3.14
   * 
   * 
   * @param {Number} n The number to be rounded
   * @param {Number} places Decimal places
   * 
   * @returns {Number} Rounded number
   */

  module.exports.round = function (n, places = 0) {
    typeCheck({
      param: n,
      expected: 'number'
    }, {
      param: places,
      expected: 'number'
    })

    places = Math.pow(10, places)

    return Math.floor(n * places) / places;
  }  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment