I recently came across a question in an interview and am stumped at how to solve it. I would really appreciate any assistance.
The question asked me to create a function that received a number as a parameter (599) and returns a different number, but will also work in reverse. The issue is that I was not permitted to use any sort of conditional operator e.g. if, switch etc...
This was as far as I got:
function changeValue(v) {
// return 599 if 395 passed and vice versa
}
Run Code Online (Sandbox Code Playgroud)
Use an object
function changeValue(v) {
const obj = {'395': 599, '599': 395};
return obj[v];
}
console.log(changeValue(395));
console.log(changeValue(599));Run Code Online (Sandbox Code Playgroud)
how about this:
function changeValue(v) {
return (599 + 395) - v;
}
Run Code Online (Sandbox Code Playgroud)
from a programming perspective, this isn't as good a solution as the one that uses an object, because an object (map/dictionary) is easier to extend to other values.
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |