Search
⌘K

Array

Utilities for working with arrays.

Example Usage

import { getLastArrayItem } from "./array"

// getLastArrayItem(any[]) => any
getLastArrayItem([0, 100, 50]);
// ⏬
50

// createArrayWithLength
createArrayWithLength(2);
// ⏬
['_', '_']

Dependencies

No dependencies

Auto Install

npx shadcn@latest add https://shadcn-registry-ts.vercel.app/r/util-array.json

Manual Install

array.ts
/**
 * Source: http://localhost:3000
 */

export const getLastArrayItem = <T>(array: T[]) => array[array.length - 1];


/** Create an array with length, that you can `.map` on */
export const createArrayWithLength = (length: number) => Array(length).fill('_');

Test

array.test.ts
import { describe, it, expect } from 'vitest';

import { getLastArrayItem, createArrayWithLength } from './array';

describe('array - getLastArrayItem', () => {

  it('do it', () => {
    expect(getLastArrayItem([])).toBeUndefined();
    expect(getLastArrayItem([1, 2, 3])).toBe(3);
  });

});

describe('array - createArrayWithLength', () => {

  it('do it', () => {
    expect(createArrayWithLength(3).length).toBe(3);
    expect(createArrayWithLength(2).map((_, i) => i)).toEqual([0, 1]);
  });

});

Command Palette

Search for a command to run...