0.2.1 • Published 2 years ago

limited-size-array v0.2.1

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

limited-size-array

Expanded Array with max_size parameter

Getting started

Installation:

npm i limited-size-array

then:

import { LimitedArray } from  "limited-size-array" // ES6
// or
const LimitedArray = require("limited-size-array") // CommonJS

Creating limited array:

const arr = new LimitedArrey([1, 2, 3], 3)
console.log(arr) // LimitedArray(3) [ 1, 2, 3 ]

arr.push(4)
console.log(arr) // LimitedArray(3) [ 1, 2, 3 ]
// arr.length is equal to max_length (3), so arr.push() is ignored

LimitedArray class

LimitedArray extends Array

constructor(array, max_length, func)

array: Array

The initial values ​​of the array (can be empty)

max_length: Number

Maximum length of the created LimitedArray (0-Infinity, but not less than array.length)

func?: Function(arr, fn, args)

The function that will be executed if push/unshift method causes causes the array to overflow

arr: Array – array that overflows due to a function
fn: Function - function that caused an overflow
args: Array - arguments of fn

Methods that create new array (like .concat(), .filter() etc) return Array (not LimitedArray)

Examples

Limited queue

If the array overflows, it deletes the last values ​​and inserts new ones

const arr = new LimitedArray([1, 2, 3], 3, (arr, fn, args) => {
    arr.pop()
    return fn(...args) // recursion
})
console.log(arr) // LimitedArray(3) [ 1, 2, 3 ]

arr.unshift(0)
console.log(arr) // LimitedArray(3) [ 0, 1, 2 ]

also works with multiple arguments

arr.unsfift(-2, -1)
console.log(arr) // LimitedArray(3) [ -2, -1, 0]

Modified one

The array waits to be filled and then performs all functions

const arr = new LimitedArray(
    [() => console.log("Hello"), () => console.log("World")],
    2,
    (arr, fn, args) => {
	    arr.forEach(item => item())
	    args.forEach(item => item())
	    
	    arr.length = 0
    }
)
arr.push(() => console.log("!"))
// Hello
// World
// !

console.log(arr) // LimitedArray(0) []
0.2.1

2 years ago

0.2.0

2 years ago

0.1.0

2 years ago