Skip to content

Instantly share code, notes, and snippets.

@prograhammer
Last active March 20, 2017 14:07
Show Gist options
  • Save prograhammer/c5c6f26dcf7f9cae8cbb40756504f58f to your computer and use it in GitHub Desktop.
Save prograhammer/c5c6f26dcf7f9cae8cbb40756504f58f to your computer and use it in GitHub Desktop.
selectItem (item) {
if (!this.multiple) {
this.inputValue = item
} else {
if (this.inputValue === null) {
this.inputValue = [item]
} else {
const i = this.inputValue.findIndex(i => this.getValue(i) === this.getValue(item))
if (i !== -1) {
this.inputValue.splice(i, 1)
} else {
this.inputValue.push(item)
}
}
}
if (this.autocomplete) {
this.$nextTick(() => {
this.searchValue = null
this.$refs.input.focus()
})
}
}
},
// Refactor #1
//
// Shift the reading of the eyes to a quicker vertical scan.
// No big "else". Nested small "if/else" blocks that are only 1 level deep
// are fine. Try to see if it's more readable as a ternary (not always though).
// But anymore nesting may mean you need to call a function or apply some other
// refactor.
selectItem (item) {
if (!this.multiple) {
this.inputValue = item
}
if (this.multiple && this.inputValue === null) {
this.inputValue = [item]
}
if (this.multiple && this.inputValue !== null) {
const i = this.inputValue.findIndex(i => this.getValue(i) === this.getValue(item))
if (i !== -1) {
this.inputValue.splice(i, 1)
} else {
this.inputValue.push(item)
}
}
if (this.autocomplete) {
this.$nextTick(() => {
this.searchValue = null
this.$refs.input.focus()
})
}
}
},
// Refactor #2
//
// Let's move complexity to a method. But be balanced about it.
// The Ruby on Rails folk will try to tell you that you need to refactor
// away all conditions and stuff, but you end up with method explosion
// (which means you have to jump around a lot to fully understand what's happening).
selectItem (item) {
if (!this.multiple) this.inputValue = item
if (this.multiple) this.selectItemMultiple(item)
if (this.autocomplete) {
this.$nextTick(() => {
this.searchValue = null
this.$refs.input.focus()
})
}
}
},
// Refactor #3
//
// We could see if reducing vertical space further helps or not.
// A ternary can sometimes help. Here is where coding becomes artform.
// You make judgement calls. Use a ternary, or do I lose some context
// of what I'm doing? Return early, or is the last left over code out of context?
selectItem (item) {
this.multiple ? this.selectItemMultiple(item) : this.inputValue = item
if (this.autocomplete) {
this.$nextTick(() => {
this.searchValue = null
this.$refs.input.focus()
})
}
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment