Skip to content

shift

Remove a specified number of elements from the beginning of an array and return the removed elements.

Basic Usage

typescript
import { shift } from 'radash'

const numbers = [1, 2, 3, 4, 5]

const [removed, remaining] = shift(numbers, 2)
// removed: [1, 2]
// remaining: [3, 4, 5]

Syntax

typescript
function shift<T>(
  array: readonly T[],
  count?: number
): [T[], T[]]

Parameters

  • array (readonly T[]): The array to operate on
  • count (number, optional): Number of elements to remove, defaults to 1

Return Value

Returns a tuple containing two arrays:

  • First array: The removed elements
  • Second array: The remaining elements

Examples

Remove Single Element

typescript
import { shift } from 'radash'

const fruits = ['apple', 'banana', 'cherry', 'date']

const [removed, remaining] = shift(fruits)
// removed: ['apple']
// remaining: ['banana', 'cherry', 'date']

Remove Multiple Elements

typescript
import { shift } from 'radash'

const numbers = [1, 2, 3, 4, 5, 6, 7, 8]

const [removed, remaining] = shift(numbers, 3)
// removed: [1, 2, 3]
// remaining: [4, 5, 6, 7, 8]

Remove All Elements

typescript
import { shift } from 'radash'

const items = ['a', 'b', 'c']

const [removed, remaining] = shift(items, 3)
// removed: ['a', 'b', 'c']
// remaining: []

Remove More Elements Than Array Length

typescript
import { shift } from 'radash'

const items = ['a', 'b', 'c']

const [removed, remaining] = shift(items, 5)
// removed: ['a', 'b', 'c']
// remaining: []

Handle Empty Arrays

typescript
import { shift } from 'radash'

const emptyArray: number[] = []

const [removed, remaining] = shift(emptyArray, 2)
// removed: []
// remaining: []

Handle Object Arrays

typescript
import { shift } from 'radash'

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'Diana' }
]

const [removedUsers, remainingUsers] = shift(users, 2)
// removedUsers: [
//   { id: 1, name: 'Alice' },
//   { id: 2, name: 'Bob' }
// ]
// remainingUsers: [
//   { id: 3, name: 'Charlie' },
//   { id: 4, name: 'Diana' }
// ]

Using in Queue Processing

typescript
import { shift } from 'radash'

class Queue<T> {
  private items: T[] = []

  enqueue(item: T) {
    this.items.push(item)
  }

  dequeue(count: number = 1): T[] {
    const [removed, remaining] = shift(this.items, count)
    this.items = remaining
    return removed
  }

  peek(): T | undefined {
    return this.items[0]
  }

  size(): number {
    return this.items.length
  }
}

const queue = new Queue<number>()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)

const dequeued = queue.dequeue(2)
console.log(dequeued) // [1, 2]
console.log(queue.size()) // 1

Processing Paginated Data

typescript
import { shift } from 'radash'

function processBatch<T>(items: T[], batchSize: number): T[][] {
  const batches: T[][] = []
  let remaining = [...items]

  while (remaining.length > 0) {
    const [batch, newRemaining] = shift(remaining, batchSize)
    batches.push(batch)
    remaining = newRemaining
  }

  return batches
}

const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const batches = processBatch(data, 3)

console.log(batches)
// [
//   [1, 2, 3],
//   [4, 5, 6],
//   [7, 8, 9],
//   [10]
// ]

Processing Time Series Data

typescript
import { shift } from 'radash'

interface TimeSeriesPoint {
  timestamp: number
  value: number
}

const timeSeriesData: TimeSeriesPoint[] = [
  { timestamp: 1000, value: 10 },
  { timestamp: 2000, value: 20 },
  { timestamp: 3000, value: 30 },
  { timestamp: 4000, value: 40 },
  { timestamp: 5000, value: 50 }
]

// Remove the first two data points
const [removedPoints, remainingPoints] = shift(timeSeriesData, 2)

console.log('Removed:', removedPoints)
// [
//   { timestamp: 1000, value: 10 },
//   { timestamp: 2000, value: 20 }
// ]

console.log('Remaining:', remainingPoints)
// [
//   { timestamp: 3000, value: 30 },
//   { timestamp: 4000, value: 40 },
//   { timestamp: 5000, value: 50 }
// ]

Processing String Arrays

typescript
import { shift } from 'radash'

const words = ['hello', 'world', 'javascript', 'typescript', 'react']

const [removedWords, remainingWords] = shift(words, 2)
// removedWords: ['hello', 'world']
// remainingWords: ['javascript', 'typescript', 'react']

// Join removed words into a sentence
const sentence = removedWords.join(' ')
console.log(sentence) // 'hello world'

Processing Number Arrays

typescript
import { shift } from 'radash'

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Remove the first 5 numbers
const [removedNumbers, remainingNumbers] = shift(numbers, 5)

console.log('Removed numbers:', removedNumbers) // [1, 2, 3, 4, 5]
console.log('Remaining numbers:', remainingNumbers) // [6, 7, 8, 9, 10]

// Calculate the sum of removed numbers
const sum = removedNumbers.reduce((acc, num) => acc + num, 0)
console.log('Sum of removed numbers:', sum) // 15

Processing Mixed Type Arrays

typescript
import { shift } from 'radash'

const mixedArray = [1, 'hello', true, { key: 'value' }, [1, 2, 3]]

const [removed, remaining] = shift(mixedArray, 3)
// removed: [1, 'hello', true]
// remaining: [{ key: 'value' }, [1, 2, 3]]

Notes

  1. Keep original array unchanged: shift does not modify the original array, but returns new arrays
  2. Return tuple: Returns a tuple containing two arrays
  3. Boundary handling: If count exceeds array length, all elements will be removed
  4. Performance: Time complexity is O(n), where n is the array length
  5. Empty arrays: Calling on empty arrays returns two empty arrays

Differences from Other Methods

  • Array.prototype.shift(): Only removes one element and returns that element
  • shift(): More flexible version provided by radash, can remove multiple elements
  • slice(): Returns subarray, does not modify original array
  • splice(): Modifies the original array

Practical Application Scenarios

  1. Queue processing: Implement FIFO queue operations
  2. Batch processing: Process large amounts of data in batches
  3. Time series: Process sliding windows of time series data
  4. Cache management: Remove old data from cache
  5. Stream processing: Process elements in data streams

Released under the MIT License.