有意思
最近很火的github上的库30-seconds-of-code,特别有意思,代码也很优雅。
- 能学 es6
- 自己翻译,能学英语
- 代码很美,很优雅,美即正义
- 函数式表达,享受
arrayGcd
Calculates the greatest common denominator (gcd) of an array of numbers.
Use
Array.reduce()and thegcdformula (uses recursion) to calculate the greatest common denominator of an array of numbers.const arrayGcd = arr =>{ const gcd = (x, y) => !y ? x : gcd(y, x % y); return arr.reduce((a,b) => gcd(a,b)); } // arrayGcd([1,2,3,4,5]) -> 1 // arrayGcd([4,8,12]) -> 4
计算数组的最大公约数。
使用Array.reduce()和gcd公式(使用递归)来计算一个数组的最大公约数。
➜ code cat arrayGcd.js
const arrayGcd = arr => {
const gcd = (x, y) => !y ? x : gcd(y, x % y);
return arr.reduce((a, b) => gcd(a, b));
}
console.log(arrayGcd([1, 2, 3, 4, 5]));
console.log(arrayGcd([4, 8, 12]));
➜ code node arrayGcd.js
1
4
gcd即欧几里德算法,具体不表,自查。这里用到了数组的 reduce 方法,相当简洁,reduce 不太了解的话,看下mdn就明白。
arrayLcm
Calculates the lowest common multiple (lcm) of an array of numbers.
Use
Array.reduce()and thelcmformula (uses recursion) to calculate the lowest common multiple of an array of numbers.const arrayLcm = arr =>{ const gcd = (x, y) => !y ? x : gcd(y, x % y); const lcm = (x, y) => (x*y)/gcd(x, y) return arr.reduce((a,b) => lcm(a,b)); } // arrayLcm([1,2,3,4,5]) -> 60 // arrayLcm([4,8,12]) -> 24
计算一个数组的最小公倍数。
使用Array.reduce()和lcm公式(使用递归)来计算一个数组的最大公约数。
➜ code cat arrayLcm.js
const arrayLcm = arr => {
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
const lcm = (x, y) => x * y / gcd(x, y);
return arr.reduce((a, b) => lcm(a, b));
};
console.log(arrayLcm([1, 2, 3, 4, 5]));
console.log(arrayLcm([4, 8, 12]));
➜ code node arrayLcm.js
60
24
lcm算法用到了前面的gcd算法,关键点是两个数的最大公约数和最小公倍数的乘积正好就是这两个数的乘积。
arrayMax
Returns the maximum value in an array.
Use
Math.max()combined with the spread operator (...) to get the maximum value in the array.const arrayMax = arr => Math.max(...arr); // arrayMax([10, 1, 5]) -> 10
返回数组中最大的值。
使用Math.max()和ES6的扩展运算符…返回数组中最大的值。
➜ code cat arrayMax.js
const arrayMax = arr => Math.max(...arr);
console.log(arrayMax([10, 1, 5]));
➜ code node arrayMax.js
10
实际上就是Math.max()干的事,没啥可说的了。
arrayMin
Returns the minimum value in an array.
Use
Math.min()combined with the spread operator (...) to get the minimum value in the array.const arrayMin = arr => Math.min(...arr); // arrayMin([10, 1, 5]) -> 1
返回数组中最小的值。
使用Math.min()和ES6的扩展运算符…返回数组中最小的值。
➜ code cat arrayMin.js
const arrayMin = arr => Math.min(...arr);
console.log(arrayMin([10, 1, 5]));
➜ code node arrayMin.js
1
实际上就是Math.min()干的事,没啥可说的了。
全文太长,放个全文链接吧:
Javscript30 秒, 从入门到放弃