« Back to the index

Function.prototype.buildTransformer examples

The "transformer" method allow the programmer to filter the input and output of any existing function:
newfunction = function.buildTransformer(prefuntion, postfunction);
The "prefunction" is a function that accept the same parameters as the main function, modify them, and finally reinject them into the main function. The return value must be an array with the parameters in the same order.
This function is very usefull to verify the validity of the parameters and modify them if there is any problem, put default values, etc.
The "postfunction" is a function that accept the returned result of the main function, and will modify it return the modified value to the caller.

Let's use a basic function that calculates the difference between 2 values:
function test(var1, var2) { return var2-var1; }
View the result of this code
The pre function check if the first parameter is superior to the second one. If not, it will invert them.
var pretest = test.buildTransformer( function(v1, v2) // pre function, check the min/max on arguments { if (WA.isNumber(v1) && WA.isNumber(v2) && v1 > v2) return [v2, v1]; return [v1, v2]; }, null // no post function );
View the result of this code
The post function checks if the result is positive. If not, it will change the sign.
The two functions are identical in final returned result: a positive number.
var posttest = test.buildTransformer( null, // no pre function function(res) // post function, check the sign { return (res>0?res:-res); } );
View the result of this code


« Back to the index