Skip to content

Instantly share code, notes, and snippets.

@gund
Created January 21, 2019 09:47
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 gund/4f8872da12100ea7ff29f24f9af339ad to your computer and use it in GitHub Desktop.
Save gund/4f8872da12100ea7ff29f24f9af339ad to your computer and use it in GitHub Desktop.
Example how you can convert data without branching
// 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