Skip to content

shift

从数组的开头移除指定数量的元素,并返回被移除的元素。

基础用法

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]

语法

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

参数

  • array (readonly T[]): 要操作的数组
  • count (number, 可选): 要移除的元素数量,默认为1

返回值

返回一个元组,包含两个数组:

  • 第一个数组:被移除的元素
  • 第二个数组:剩余的元素

示例

移除单个元素

typescript
import { shift } from 'radash'

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

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

移除多个元素

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]

移除所有元素

typescript
import { shift } from 'radash'

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

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

移除超过数组长度的元素

typescript
import { shift } from 'radash'

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

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

处理空数组

typescript
import { shift } from 'radash'

const emptyArray: number[] = []

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

处理对象数组

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' }
// ]

在队列处理中使用

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

处理分页数据

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]
// ]

处理时间序列数据

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 }
]

// 移除前两个数据点
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 }
// ]

处理字符串数组

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']

// 将移除的单词连接成句子
const sentence = removedWords.join(' ')
console.log(sentence) // 'hello world'

处理数字数组

typescript
import { shift } from 'radash'

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

// 移除前5个数字
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]

// 计算移除数字的总和
const sum = removedNumbers.reduce((acc, num) => acc + num, 0)
console.log('Sum of removed numbers:', sum) // 15

处理混合类型数组

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]]

注意事项

  1. 保持原数组不变: shift 不会修改原数组,而是返回新的数组
  2. 返回元组: 返回一个包含两个数组的元组
  3. 边界处理: 如果count超过数组长度,会移除所有元素
  4. 性能: 时间复杂度为 O(n),其中 n 是数组长度
  5. 空数组: 对空数组调用会返回两个空数组

与其他方法的区别

  • Array.prototype.shift(): 只移除一个元素并返回该元素
  • shift(): radash提供的更灵活的版本,可以移除多个元素
  • slice(): 返回子数组,不修改原数组
  • splice(): 会修改原数组

实际应用场景

  1. 队列处理: 实现先进先出的队列操作
  2. 批处理: 分批处理大量数据
  3. 时间序列: 处理时间序列数据的滑动窗口
  4. 缓存管理: 移除缓存中的旧数据
  5. 流处理: 处理数据流中的元素

Released under the MIT License.