JavaScript30秒, 从入门到放弃

开发 前端
最近很火的github上的库30-seconds-of-code ,特别有意思,代码也很优雅。能学es6、自己翻译,能学英语、代码很美,很优雅,美即正义、函数式表达,享受等。

有意思

最近很火的 github 上的库 30-seconds-of-code ,特别有意思,代码也很优雅。

[[214475]]

  1. 能学es6
  2. 自己翻译,能学英语
  3. 代码很美,很优雅,美即正义
  4. 函数式表达,享受

arrayGcd

Calculates the greatest common denominator (gcd) of an array of numbers.

Use Array.reduce() and the gcd formula (uses recursion) to calculate the greatest common denominator of an array of numbers.

 

  1. const arrayGcd = arr =>{ 
  2.   const gcd = (x, y) => !y ? x : gcd(y, x % y); 
  3.   return arr.reduce((a,b) => gcd(a,b)); 
  4. // arrayGcd([1,2,3,4,5]) -> 1 
  5. // arrayGcd([4,8,12]) -> 4 

计算数组的***公约数。

使用 Array.reduce() 和 gcd 公式(使用递归)来计算一个数组的***公约数。

 

  1. ➜  code cat arrayGcd.js 
  2. const arrayGcd = arr => { 
  3.     const gcd = (x, y) => !y ? x : gcd(y, x % y); 
  4.     return arr.reduce((a, b) => gcd(a, b)); 
  5.  
  6. console.log(arrayGcd([1, 2, 3, 4, 5])); 
  7. console.log(arrayGcd([4, 8, 12])); 
  8. ➜  code node arrayGcd.js 

gcd 即欧几里德算法,具体不表,自查。这里用到了数组的reduce方法,相当简洁,reduce不太了解的话,看下 mdn 就明白。

arrayLcm

Calculates the lowest common multiple (lcm) of an array of numbers.

Use Array.reduce() and the lcm formula (uses recursion) to calculate the lowest common multiple of an array of numbers.

 

  1. const arrayLcm = arr =>{ 
  2.  const gcd = (x, y) => !y ? x : gcd(y, x % y); 
  3.  const lcm = (x, y) => (x*y)/gcd(x, y)  
  4.  return arr.reduce((a,b) => lcm(a,b)); 
  5. // arrayLcm([1,2,3,4,5]) -> 60 
  6. // arrayLcm([4,8,12]) -> 24 

计算一个数组的最小公倍数。

使用 Array.reduce() 和 lcm 公式(使用递归)来计算一个数组的***公约数。

 

  1. ➜  code cat arrayLcm.js 
  2. const arrayLcm = arr => { 
  3.   const gcd = (x, y) => (!y ? x : gcd(y, x % y)); 
  4.   const lcm = (x, y) => x * y / gcd(x, y); 
  5.   return arr.reduce((a, b) => lcm(a, b)); 
  6. }; 
  7.  
  8. console.log(arrayLcm([1, 2, 3, 4, 5])); 
  9. console.log(arrayLcm([4, 8, 12])); 
  10. ➜  code node arrayLcm.js 
  11. 60 
  12. 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.

 

  1. const arrayMax = arr => Math.max(...arr); 
  2. // arrayMax([10, 1, 5]) -> 10 

返回数组中***的值。

使用 Math.max() 和 ES6 的扩展运算符 … 返回数组中***的值。

 

  1. ➜  code cat arrayMax.js 
  2. const arrayMax = arr => Math.max(...arr); 
  3.  
  4. console.log(arrayMax([10, 1, 5])); 
  5. ➜  code node arrayMax.js 
  6. 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.

 

  1. const arrayMin = arr => Math.min(...arr); 
  2. // arrayMin([10, 1, 5]) -> 1 

返回数组中最小的值。

使用 Math.min() 和 ES6 的扩展运算符 … 返回数组中最小的值。

 

  1. ➜  code cat arrayMin.js 
  2. const arrayMin = arr => Math.min(...arr); 
  3.  
  4. console.log(arrayMin([10, 1, 5])); 
  5. ➜  code node arrayMin.js 

实际上就是 Math.min() 干的事,没啥可说的了。

chunk

Chunks an array into smaller arrays of a specified size.

Use Array.from() to create a new array, that fits the number of chunks that will be produced. Use Array.slice() to map each element of the new array to a chunk the length of size . If the original array can't be split evenly, the final chunk will contain the remaining elements.

 

  1. const chunk = (arr, size) => 
  2.  Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)); 
  3. // chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]] 

按照给定的 size 将一个数组切分成含有 size 个数的更小数组块的数组。

使用 Array.from() 生产新的符合定义的数组。使用 Array.slice() 来截取指定 size 个元素组成新的数组块。如果原数组长度不能被 size 整除,***的剩余的那些元素将归属于***一个块。

 

  1. ➜  code cat chunk.js 
  2. const chunk = (arr, size) => 
  3.   Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => 
  4.     arr.slice(i * size, i * size + size
  5.   ); 
  6.  
  7. console.log(chunk([1, 2, 3, 4, 5], 2)); 
  8. ➜  code node chunk.js 
  9. [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ] 

Array.from(arrayLike, mapFn, thisArg) 这个方法呢,***个参数是一个类数组或者可迭代的对象,第二个参数是一个应用在每一个数组元素上的方法,第三个参数就是改变 this 的指向了。通俗说就是指定谁是你的爸爸。

这里用了一个 { length: Math.ceil(arr.length / size) } 迭代对象, length 指定了迭代次数,即按照 size 分块后的数组长度,正好就是原数组长度除以 size 向上取整的值。向上取整就是为了满足不能完全整除的情况。比如5个元素按照2个一组进行分块,分了两组两个元素的,剩***一个元素成了独立组,总长为3。

(v, i) ,由于迭代的时候数组在每一个位置上都是以 undefined 初始化的,所以 v 一直都是 undefined 。

arr.slice(i * size, i * size + size) 迭代过程中每次截取 size 个数的元素组成新数组。这里的 i 就是随着迭代变化,比如 length 是3, i 就是0,1,2。

这里的迭代类似 python 里的 range 。

 

  1. ➜  code python 
  2. Python 3.6.4 (defaultDec 23 2017, 10:37:40) 
  3. [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin 
  4. Type "help""copyright""credits" or "license" for more information. 
  5. >>> import math 
  6. >>> arr = [1,2,3,4,5] 
  7. >>> size = 2 
  8. >>> for i in range(math.ceil(len(arr) / size)): 
  9. ...     print('index: ', i) 
  10. ... 
  11. index:  0 
  12. index:  1 
  13. index:  2 

compact

Removes falsey values from an array.

Use Array.filter() to filter out falsey values ( false , null , 0 , "" , undefined , and NaN ).

 

  1. const compact = arr => arr.filter(Boolean); 
  2. // compact([0, 1, false, 2, '', 3, 'a''e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 

移除掉数组里 falsey 的元素。(这个 falsey 不太好翻译,不是错误的意思,而是该值布尔运算值为 false 的意思,我个人常用 !! 进行判断)。

使用 Array.filter() 把 false 、 null 、 0 、 "" 、 undefined 和 NaN 这些 falsey 过滤掉。

 

  1. ➜  code cat compact.js 
  2. const compact = arr => arr.filter(Boolean); 
  3.  
  4. console.log(compact([0, 1, false, 2, "", 3, "a""e" * 23, NaN, "s", 34])); 
  5. ➜  code node compact.js 
  6. [ 1, 2, 3, 'a''s', 34 ] 

Array.prototype.filter() 干的,没啥好说。

countOccurrences

Counts the occurrences of a value in an array.

Use Array.reduce() to increment a counter each time you encounter the specific value inside the array.

 

  1. const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0); 
  2. // countOccurrences([1,1,2,1,2,3], 1) -> 3 

统计一个元素在一个数组中出现的次数。

使用 Array.reduce() 在遍历过程中如果指定元素在数组中出现,则增加它的次数值,默认次数为0。

 

  1. ➜  code cat countOccurrences.js 
  2. const countOccurrences = (arr, value) => 
  3.   arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0); 
  4.  
  5. console.log(countOccurrences([1, 1, 2, 1, 2, 3], 1)); 
  6. console.log(countOccurrences([1, 1, 2, 1, 2, 3], 5)); 
  7. ➜  code node countOccurrences.js 

三元运算符 (v === value ? a + 1 : a + 0) 遍历过程中判断遍历数组值 v 是否严格等于指定值 value ,是,次数 a+1 ;否, a+0 。

***的一个逗号后面的0,是这个初始值,即 a=0 ,这个懂 reduce 方法都知道,特别指出是,因为这个函数一定会有返回值,如果指定元素没有在数组中出现一次,返回值是 0 ,所以必须得初始化为 0 。

deepFlatten

Deep flattens an array.

Use recursion. Use Array.concat() with an empty array ( [] ) and the spread operator ( ... ) to flatten an array. Recursively flatten each element that is an array.

 

  1. const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); 
  2. // deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5] 

深度摊平一个数组。

使用递归方法。结合 Array.concat() 、空数组 [] 和 ES6 的扩展运算符 … 来摊平一个数组,如果摊平的元素还是一个数组,就再递归运用该方法。

 

  1. ➜  code cat deepFlatten.js 
  2. const deepFlatten = arr => 
  3.   [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); 
  4.  
  5. console.log(deepFlatten([1, [2], [[3], 4], 5])); 
  6. ➜  code node deepFlatten.js 
  7. [ 1, 2, 3, 4, 5 ] 

三元运算符 (Array.isArray(v) ? deepFlatten(v) : v) 判断 v 是否是一个数组,是,返回递归运用 deepFlatten(v) 后的值;否,直接返回 v 。

[].concat(...arr.map(fn)) 用空数组把 map 运算产生的数组进行 … 扩展运算值拼接成结果数组返回。

该方法是深度摊平方法,在很多时候还有特定的摊平一层的需求, underscore 就有。实现的方法就是再加一个标志参数进行处理即可。具体不讲了。

应该会写一个系列,今天先写到这,明天继续。

责任编辑:未丽燕 来源: SegmentFault
相关推荐

2016-08-03 16:01:47

GitLinux开源

2019-07-02 14:17:18

API网关网关流量

2017-03-25 20:30:15

2020-07-07 10:50:19

Python丄则表达文本

2019-08-21 14:35:18

压缩文件优化过程Java

2022-01-17 08:52:32

CPUCPU工具显卡

2022-03-28 11:00:34

JVMJava对象

2021-11-08 07:11:49

决策树数据分类器

2020-11-12 18:51:43

Java编程语言

2022-04-19 11:25:31

JVMZGC垃圾收集器

2020-04-10 15:05:09

深度学习人工智能蒸馏

2018-01-26 14:35:16

程序员入门经历

2019-06-23 15:21:42

Google谷歌平板

2021-05-11 11:08:37

电脑病毒软件

2021-08-02 06:49:46

Flutter Router安全

2022-09-30 15:46:26

Babel编译器插件

2021-10-25 05:54:59

SSD固态硬盘存储

2022-04-21 08:20:33

CPU换盖CPU

2021-10-15 22:19:15

电脑蓝屏重启

2021-02-06 22:10:12

宏定义处理器代码
点赞
收藏

51CTO技术栈公众号