"use strict" ;
const generateValidator = require ( "./generate-validator" ) ;
module . exports = function guardFunction ( args , returnType , func ) {
let rules = args . map ( ( arg ) => {
return generateValidator ( arg ) ;
} ) ;
let returnValueValidator = generateValidator ( returnType ) ;
let guardedFunction = function ( ... params ) {
let paramsWithDefaults = new Array ( params . length ) ;
/* TODO: Can this be made faster by manually incrementing the index outside of the loop, or even by using forEach? ref https://jsperf.com/for-of-vs-foreach-with-index */
for ( let [ i , rule ] of rules . entries ( ) ) {
let validatorResult = rule . call ( this , params [ i ] ) ;
if ( validatorResult === true ) {
paramsWithDefaults [ i ] = params [ i ] ;
} else if ( validatorResult . _default !== undefined ) {
paramsWithDefaults [ i ] = validatorResult . _default ;
} else {
throw validatorResult ;
}
}
let returnValue = func . apply ( this , paramsWithDefaults ) ;
let returnValueValidatorResult = returnValueValidator . call ( this , returnValue ) ;
if ( returnValueValidatorResult === true ) {
return returnValue ;
} else if ( returnValueValidatorResult . _default !== undefined ) {
return returnValueValidatorResult . default ;
} else {
throw returnValueValidatorResult ;
}
} ;
guardedFunction . _guardedArgs = args ;
guardedFunction . _guardedReturnType = returnType ;
guardedFunction . _guardedFunction = func ;
return guardedFunction ;
} ;