Created
January 21, 2019 09:47
-
-
Save gund/4f8872da12100ea7ff29f24f9af339ad to your computer and use it in GitHub Desktop.
Example how you can convert data without branching
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
// function with branching | |
function giveAppleOrOrange(condition) { | |
if (condition) { | |
return 'apple'; | |
} else { | |
return 'orange'; | |
} | |
} | |
// function without branching | |
function giveAppleOrOrange(condition) { | |
const apple = [97,112,112,108,101]; // apple | |
const orange = [111,114,97,110,103,101]; // orange | |
const appleFlag = condition | 0; | |
const orangeFlag = 1 - appleFlag; | |
const trueApple = apple.map(n => n * appleFlag); | |
const trueOrange = orange.map(n => n * orangeFlag); | |
const res = trueOrange.map((a, i) => a | trueApple[i]); | |
const resStr = res.map(n => String.fromCharCode(n)).join(''); | |
return resStr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment