Skip to content

Instantly share code, notes, and snippets.

@tomprogers
Created May 15, 2017 21:20
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 tomprogers/8e5df420904124f5a83cb43903f21a4c to your computer and use it in GitHub Desktop.
Save tomprogers/8e5df420904124f5a83cb43903f21a4c to your computer and use it in GitHub Desktop.
needless eloquence

one of those moments of programming eloquence you hope for, discovered to be unneeded immediately upon finishing it

the final code:

handleWordClick = (word, event) => {
	let isShiftClick = (this.state.shiftActive);
	let [ hasClickFn , hasShiftClickFn ] = [ 'onClick', 'onShiftClick' ].map((p) => (typeof this.props[p] === 'function'));
	
	if(isShiftClick && hasShiftClickFn) {
		return this.props.onShiftClick(event, word);
	} else if(hasClickFn) {
		return this.props.onClick(event, word);
	}
}

why it's eloquent:

the straightforward way to write that would be:

handleWordClick = (word, event) => {
	let isShiftClick = (this.state.shiftActive);
	
	let [ hasClickFn , hasShiftClickFn ] = [ 'onClick', 'onShiftClick' ].map((p) => (typeof this.props[p] === 'function'));
	
	if(isShiftClick && hasShiftClickFn) {
		return this.props.onShiftClick(event, word);
	
	else if(isShiftClick & hasClickFn) {
		return this.props.onClick(event, word);
	
	} else if(hasClickFn) {
		return this.props.onClick(event, word);
	
	}
}

the eloquence comes in when you notice that the second & third branches are identical, and that the third case is sufficient to capture both scenarios and separate them from the predictably bad scenario (throw when attempting to invoke a method that wasn't provided) given the details of the first test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment