该算法题来自于 codewars【语言: javascript】,翻译如有误差,敬请谅解~
- 场景
Philip 刚刚四岁,他想知道他将来在未来几年多少岁,比如2090年或3044年。他的父母无法跟上计算,所以他们请求你帮助他们写一个程序,可以回答 Philip 无休止的问题。
- 任务
- 写一个函数,它会有两个参数:出生年份和想要计算的年数。由于 Philip 每天都乐忠于玩这个游戏,他很快就想知道他还有多久出生,所以你的函数需要计算未来和过去两个时期。
- 提供以下格式的输出:
1. 对于未来的日期:“You are ... year(s) old.”。
2. 对于过去的日期:“You will be born in ... year(s).”。
3. 如果出生年份等于要求计算的日期:“You were born this very year!” - “...”将由数字代替。请注意,您需要区别 “year” 和 “years” ,这个取决于计算出来的结果。
- 解答
- 其一
const calculateAge = (birth, year) => {
const result = year - birth;
let old = '';
if (result > 0){
old = "You are " + (result > 1 ? result + " years old." : result + " year old.")
} else {
if(!!result){
old = "You will be born in "+ (-result > 1 ? -result + " years." : -result + " year." )
} else {
old = "You were born this very year!";
}
}
return old;
}
- 其二
function calculateAge(m, n) {
if(m == n) return 'You were born this very year!';
var year = Math.abs(m-n) == 1 ? 'year' : 'years';
if(m < n) return "You are "+(n-m)+' '+year+' old.';
if(m > n) return "You will be born in "+(-n+m)+' '+year+'.';
}
- 其三
var calculateAge = (b,c) => {
r = c-b;
switch(true) {
case (r>1): return "You are " + r + " years old."; break;
case (r===1): return "You are 1 year old."; break;
case (r===0): return "You were born this very year!"; break;
case (r===-1): return "You will be born in 1 year."; break;
case (r<-1): return "You will be born in " + (-r) + " years."; break;
}
}
- 其四
// es6 模板字符串
function calculateAge(a,b) {
return a > b
? `You will be born in ${a-b} year${a-b==1?"":"s"}.`
: a < b ? `You are ${b-a} year${b-a==1?"":"s"} old.` : `You were born this very year!`
}
- 其五
const calculateAge = (a, b) => 'You ' + (a == b ? 'were born this very year!' : a > b ? `will be born in ${a - b} year${a - b != 1 ? 's' : ''}.`: `are ${b - a} year${b - a != 1 ? 's' : ''} old.`);
- 其六
function calculateAge(birth, query) {
const diff = Math.max(...arguments) - Math.min(...arguments);
const isPlural = diff > 1 ? 's' : '';
return {
[birth < query]: `You are ${diff} year${isPlural} old.`,
[birth > query]: `You will be born in ${diff} year${isPlural}.`,
[birth === query]: "You were born this very year!"
}[true]
}