1.0.2 • Published 6 years ago

create-empty-array v1.0.2

Weekly downloads
3
License
MIT
Repository
github
Last release
6 years ago

Travis build status Codecov branch npm downloads MIT License

gzip size size

Maintainability PRs Welcome

Why?

In React, there are times when you have a number and want to iterate over it.

You might do something like this:

import React from "react";

const MyList = ({ length }) => {
  let temporaryArray = [];
  let i = 0;
  while (i < length) {
    temporaryArray.push(undefined);
    i++;
  }

  return (
    <ul>
      {temporaryArray.map((_, index) => {
        <li key={index}>Another one</li>
      })}
    </ul>  
  );
};

This utility creates an empty array with length number which you can then map over.

import React from "react";
import createEmptyArray from "create-empty-array";

const MyList = ({ length }) => {
  return (
    <ul>
      {createEmptyArray(length).map((_, index) => {
        <li key={index}>Another one</li>
      })}
    </ul>  
  );
};

Getting started

npm install --save create-empty-array

Usage

import createEmptyArray from "create-empty-array";

const emptyArray = createEmptyArray(3);
// [undefined, undefined, undefined]

const mapOverEmptyArray = emptyArray.map(() => "hi");
// ["hi", "hi", "hi"]

Performance

See this performance test on jsperf.