New to Typescript and seeking some improvements for the following code to find an application available language from the browser language preference.
@Component
export default class Foo extends Vue {
...
created() {
const lang = findLang();
...
}
...
}
function findLang(): string {
for(const lang of navigator.languages ) {
if (lang.startsWith('en')) {
return 'en';
}
if (lang.startsWith('es')) {
return 'es';
}
}
return 'en';
}
I can think of a few improvements above the code without a success. Moving the findLang function to the Foo class. It works functionally but falls on the test (npm test). Also, it would be better to have a lambda instead of a function or method as the function is used only once. But the code
const lang = navigator.languages.forEach( l => {
if (l.startsWith('en')) {
return 'en';
}
if (l.startsWith('es')) {
return 'es';
}
}
);
yields blank value.
How to make those improvements?
CodePudding user response:
Keep it as it is.
One major surprise you see already is that forEach
isn't returning anything, which is correct: forEach
has an undefined
return value. To apply a lambda to each value in an array, you want map
instead....but even then you would wind up with an array with some undefined
results, which you would then need to filter and return the first value of. It won't get you the short-circuiting behavior that your return
with a loop will get you.
CodePudding user response:
To me it makes more sense to define class methods since you already have the class. If that works, but the test fails, isn't the problem with the test?
@Component
export default class Foo extends Vue {
...
created() {
const lang = this.findLang();
}
findLang(): string {
for(const lang of navigator.languages ) {
if (lang.startsWith('en')) {
return 'en';
}
if (lang.startsWith('es')) {
return 'es';
}
}
return 'en';
}
}