欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

有点意思的npm package

程序员文章站 2022-05-31 11:37:50
...

array-flatten

  • 功能
    将一个嵌套数组展平
  • 安装
npm install --save array-flatten
  • 使用
//ES6
//import {flatten} from "array-flatten";

//AMD
const flatten = require("array-flatten");
const arr = ['hello',['world'],[['have'],['a'],['nice'],['day']]];

const res = flatten(arr);
console.log(res);//[ 'hello', 'world', 'have', 'a', 'nice', 'day' ]

const res2 = flatten(arr,1);
console.log(res2);//[ 'hello', 'world', [ 'have' ], [ 'a' ], [ 'nice' ], [ 'day' ] ]
  • 源码
    算法,递归
'use strict'

module.exports = arrayFlatten

/**
 * Recursive flatten function with depth.
 */
function flattenWithDepth (array, result, depth) {
  for (var i = 0; i < array.length; i++) {
    var value = array[i]

    if (depth > 0 && Array.isArray(value)) {
      flattenWithDepth(value, result, depth - 1)
    } else {
      result.push(value)
    }
  }

  return result
}

/**
 * Recursive flatten function. Omitting depth is slightly faster.
 */
function flattenForever (array, result) {
  for (var i = 0; i < array.length; i++) {
    var value = array[i]

    if (Array.isArray(value)) {
      flattenForever(value, result)
    } else {
      result.push(value)
    }
  }

  return result
}

/**
 * Flatten an array, with the ability to define a depth.
 */
function arrayFlatten (array, depth) {
  if (depth == null) {
    return flattenForever(array, [])
  }

  return flattenWithDepth(array, [], depth)
}
相关标签: nodejs基础