Skip to content
This repository was archived by the owner on Aug 2, 2021. It is now read-only.

Repository files navigation

Circularr

Fixed size array

Install

npm i circularr

Usage

importCircularrfrom'circularr'// Create fromconstarrFrom=Circularr.from([1,2,3,4,5])// Create new with fixed sizeconstarr=newCircularr(3)// [undefined, undefined, undefined]// fill using valuearr.fill(0)// [0, 0, 0]// shift in some valuesarr.shift(16)// [0, 0, 16]arr.shift(32)// [0, 16, 32]// check contentsconsole.log(...arr)// undefined, 16, 32 

Api

Fill

fill(value: T): this

Fills the array using value, effectively resetting it. Returns this.

constarray=newCircularr(3)// [undefined, undefined, undefined]/* mutate fill */array.fill(0)// [0, 0, 0]

Shift

shift(value: T): T

shift method pushes the value to the end of the array, wherein the first value gets popped out and returned.

constarray=newCircularr(3).fill(0)array.shift(8)// [0, 0, 8] => 0array.shift(16)// [0, 8, 16] => 0array.shift(32)// [8, 16, 32] => 0array.shift(64)// [16, 32, 64] => 8array.length// 3

Unshift

unshift(value: T): T

unshift does the opposite. It pushes the value to the front, popping the last value out.

constarray=newCircularr(3).fill(0)array.unshift(8)// [8, 0, 0] => 0array.unshift(16)// [16, 8, 0] => 0array.unshift(32)// [32, 16, 8] => 0array.unshift(64)// [64, 32, 16] => 8array.length// 3

Slice

slice(beginIndex?: number, endIndex?: number): Circularr<T>

slice does works the same way as Array.slice().

constarray=Circularr.from([1,2,3,4])constsliced=array.slice(1,3)// [2, 3]

Trim

trim(): Circularr<T>

trim returns new Circularr with removed undefined values from both ends.

constarray=newCircularr<number>(5)array.shift(1)array.shift(2)consttrimmed=array.trim()// [1, 2]

At

at(index: number): T | undefined

at returns element at the index. For negative indices - undefined is returned. For overflow indices - undefined is returned

constarray=newCircularr<number>(5)array.shift(1)array.shift(2)constval0=array.at(0)// undefinedconstval1=array.at(3)// 1constval2=array.at(4)// 2constval3=array.at(5)// undefined

WrapAt

wrapAt(index: number): T | undefined

wrapAt returns element at the index. For negative and overflow indices - the index will be wrapped around, and correct value will be returned

constarray=newCircularr<number>(5)array.shift(1)array.shift(2)constval0=array.at(0)// undefinedconstval1=array.at(3)// 1constval2=array.at(4)// 2constval3=array.at(8)// 1constval3=array.at(9)// 2

Iterable

Circularr implements iterable protocol, so it can be used with any standard iterable syntax

constarray=Circularr.from([1,2,3])// array destructuringconst[firstValue]=array// destructuring copyconstcopyToArray=[...array]// for..of syntaxfor(letvalueofarray){console.log(value)}

About

Circular fixed size array

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages