优雅灵性的JS代码

1.Create Phone Number
题目:编写一个函数,它接受一个由10个整数组成的数组(0到9之间的数组),该函数以形似(123) 456-7890的电话号码的形式返回这些数字的字符串。
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"1111

function createPhoneNumber(numbers){
    var format = "(xxx) xxx-xxxx";
    for(var i = 0; i < numbers.length; i++){
        format = format.replace('x', numbers[i]);
    }
    return format;
}

2.Find the odd int
题目:给定一个数组,找到出现奇数次的数字。
PS:将始终只有一个整数出现奇数次。findOdd([1,1,2,-2,5,2,4,4,-1,-2,5]); // => returns -1

const findOdd = (xs) => xs.reduce((a, b) => a ^ b);

3.Who likes it?
likes [] // must be “no one likes this”
likes [“Peter”] // must be “Peter likes this”
likes [“Jacob”, “Alex”] // must be “Jacob and Alex like this”
likes [“Max”, “John”, “Mark”] // must be “Max, John and Mark like this”
likes [“Alex”, “Jacob”, “Mark”, “Max”] // must be “Alex, Jacob and 2 others like this”

function likes (names) {
    var templates = [
        'no one likes this',
        '{name} likes this',
        '{name} and {name} like this',
        '{name}, {name} and {name} like this',
        '{name}, {name} and {n} others like this'
    ];
    var idx = Math.min(names.length, 4);
    return templates[idx].replace(/{name}|{n}/g, function (val) {
        return val === '{name}' ? names.shift() : names.length;
    });
}

4.Shortest Word
题目:给定一串单词,返回最短单词的长度。
字符串永远不会为空,您不需要考虑不同的数据类型。

function findShort(s){
    return Math.min.apply(null, s.split(' ').map(w => w.length));
}

5.Sum of Digits / Digital Root
题目:创建一个计算digital root的函数。
digital root是数字中各位数字的递归总和。给定n,取n各位数字之和。如果该值是两位数或者更多,则继续以这种方式递归,直到产生一位数字,这个数字就是digital root。这只适用于自然数。

function digital_root(n) {
    return (n - 1) % 9 + 1;
}

来自那些优雅灵性的JS代码片段

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值