| ▲ | Overpower0416 6 hours ago |
| export function extractSearchToken(completionToken: {
token: string;
isQuoted?: boolean;
}): string {
if (completionToken.isQuoted) {
// Remove @" prefix and optional closing "
return completionToken.token.slice(2).replace(/"$/, '');
} else if (completionToken.token.startsWith('@')) {
return completionToken.token.substring(1);
} else {
return completionToken.token;
}
}
Why even use else if with return... |
|
| ▲ | kelnos 5 hours ago | parent | next [-] |
| I always write code like that. I don't like early returns. This approximates `if` statements being an expression that returns something. |
| |
| ▲ | whilenot-dev 5 hours ago | parent | next [-] | | > This approximates `if` statements being an expression that returns something. Do you care to elaborate? "if (...) return ...;" looks closer to an expression for me: export function extractSearchToken(completionToken: { token: string; isQuoted?: boolean }): string {
if (completionToken.isQuoted) return completionToken.token.slice(2).replace(/"$/, '');
if (completionToken.token.startsWith('@')) return completionToken.token.substring(1);
return completionToken.token;
}
| |
| ▲ | catlifeonmars 5 hours ago | parent | prev [-] | | I’m not strongly opinionated, especially with such a short function, but in general early return makes it so you don’t need to keep the whole function body in your head to understand the logic. Often it saves you having to read the whole function body too. But you can achieve a similar effect by keeping your functions small, in which case I think both styles are roughly equivalent. |
|
|
| ▲ | worksonmine 5 hours ago | parent | prev [-] |
| > Why even use else if with return... What is the problem with that? How would you write that snippet? It is common in the new functional js landscape, even if it is pass-by-ref. |
| |
| ▲ | Overpower0416 5 hours ago | parent [-] | | Using guard clauses. Way more readable and easy to work with. export function extractSearchToken(completionToken: {
token: string;
isQuoted?: boolean;
}): string {
if (completionToken.isQuoted) {
return completionToken.token.slice(2).replace(/"$/, '');
}
if (completionToken.token.startsWith('@')) {
return completionToken.token.substring(1);
}
return completionToken.token;
}
|
|