javascript 一些功能函数基于数组和对象的解构

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 一些功能函数基于数组和对象的解构相关的知识,希望对你有一定的参考价值。


const map = ([ head, ...tail ], fn) => 
  (head === undefined && !tail.length) ? [] :
  (tail.length === 0) ? [ fn(head) ] :
  [ fn(head), ...map(tail, fn) ];

const filter = ([ head, ...tail ], fn) => {
  const newHead = fn(head) ? [ head ] : [];
  return tail.length ? [ ...newHead, ...(filter(tail, fn)) ] : newHead;
}

const reduce = ([ head, ...tail ], fn, initial) => {
  if(head === undefined && tail.length === 0) return initial;
  if(!initial) {
    const [ newHead, ...newTail] = tail;
    return reduce(newTail, fn, fn(head, newHead));
  }
  return tail.length ? reduce(tail, fn, fn(initial, head)) : fn(initial, head);
}

const join = ([ head, ...tail ], separator = ',') => {
  return (head === undefined && !tail.length) ? '' :
   tail.length ? head + separator + join(tail, separator) : head;
}

const qsort = ([head, ...tail]) => (head === undefined) ? [] :
[...qsort(filter(tail, a => a <= head)), ...[head, ...qsort(filter(tail, a => a > head))]];


const array = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];

const count = (tally, fruit) => {
  tally[fruit] = (tally[fruit] || 0) + 1 ;
  return tally;
}

const fib = x => x > 2 ? fib(x - 1) + fib(x - 2) : 1

const users = "Alice;alice@company.com;791-555-3931";  
const [ name, email, phone ] = users.split(";");  

const foo = [9, 10]  
const mergedArrays = [3, 5, ...foo]  


qsort(array)

以上是关于javascript 一些功能函数基于数组和对象的解构的主要内容,如果未能解决你的问题,请参考以下文章

前端基础:JavaScript对象

Javascript 继承实现方式

JavaScript对象和数组

基于对象属性对数组进行排序 - Javascript [重复]

面试中的JavaScript之函数对象数组.md

JavaScript中的全局对象,内置对象和预定义对象是啥?