Created
December 9, 2015 13:06
-
-
Save Xflofoxx/9389d165170c0c35fd12 to your computer and use it in GitHub Desktop.
How to make the definition of a function compatible backwards
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Starting | |
function myFunction(paramA, callback){ | |
console.log("I'm the old function with paramA and callback."); | |
callback(paramA); | |
} | |
// test | |
myFunction("1", function(a){console.log("I should be the parameter: "+a)}); | |
// returns | |
// I'm the old function with paramA and callback. | |
// I should be the parameter: 10 | |
// Restyle | |
// Note that paramA and callback are the same as the prior version | |
function myFunction(paramA, newParamB, newParamC, callback){ //can add as many new | |
// all you have to do is check if the function is called from the previous definition. | |
// This happened if the calling arguments are less that <num oldVersion parameters> + 1 | |
if(arguments.length < 3){ | |
oldSignature = !!(newParamB && newParamB.constructor && newParamB.call && newParamB.apply); | |
if(oldSignature){ | |
console.warn("WARN: myFunction(paramA, callback) is deprecated! Please use myFunction(paramA, newParamB, newParamC, callback)."); | |
//here you can decide or not if raise an error... (uncomment code below) | |
//throw new Error("ERROR: myFunction(paramA, callback) is deprecated! Please use myFunction(paramA, newParamB, newParamC, callback)."); | |
//if you want to go on... | |
// reassign callback | |
callback = newParamB; | |
//now you have to provide defaults for newParamB, newParamC | |
newParamBDefault = 3; //1 is the "default" for newParamB | |
//you can do that for other parameters... | |
newParamC = newParamC || 1; //1 is the "default" for newParamC | |
} else{ | |
throw new Error("ERROR: missing parameters for myFunction(paramA, newParamB, newParamC, callback)."); | |
} | |
}else{ | |
//just for using the same variable in the function body... | |
newParamBDefault = newParamB; | |
} | |
//here you can do what you want | |
paramA = paramA + newParamBDefault - newParamC; | |
callback(paramA); | |
} | |
// now the previos call | |
myFunction("1", function(a){console.log("I should be the parameter: "+a)}); | |
// returns | |
// WARN: myFunction(paramA, callback) is deprecated! Please use myFunction(paramA, newParamB, newParamC, callback). | |
// I should be the parameter: 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment