Stack.js 2.3 KB
import ListCache from './ListCache.js'
import MapCache from './MapCache.js'

/** Used as the size to enable large array optimizations. */
/** 用作启用大数组优化的大小。 */
const LARGE_ARRAY_SIZE = 200

class Stack {

  /**
   * Creates a stack cache object to store key-value pairs.
   * 创建一个堆栈缓存对象来存储键值对。
   * @private
   * @constructor
   * @param {Array} [entries] 要缓存的键值对。
   */
  constructor(entries) {
    const data = this.__data__ = new ListCache(entries)
    this.size = data.size
  }

  /**
   * Removes all key-value entries from the stack.
   * 从堆栈中删除所有键值项。
   * @memberOf Stack
   */
  clear() {
    this.__data__ = new ListCache
    this.size = 0
  }

  /**
   * Removes `key` and its value from the stack.
   * 从堆栈中删除' key '及其值。
   * @memberOf Stack
   * @param {string} key 要删除的值的键。
   * @returns {boolean} 如果条目被删除,则返回“true”,否则返回“false”。
   */
  delete(key) {
    const data = this.__data__
    const result = data['delete'](key)

    this.size = data.size
    return result
  }

  /**
   * Gets the stack value for `key`.
   * 获取' key '的堆栈值。
   * @memberOf Stack
   * @param {string} key 要获取的值的键。
   * @returns {*} 返回条目值。
   */
  get(key) {
    return this.__data__.get(key)
  }

  /**
   * Checks if a stack value for `key` exists.
   * 检查' key '的堆栈值是否存在。
   * @memberOf Stack
   * @param {string} key 输入键要检查。
   * @returns {boolean} 如果' key '的条目存在,则返回' true ',否则返回' false '。
   */
  has(key) {
    return this.__data__.has(key)
  }

  /**
   * Sets the stack `key` to `value`.
   * 将堆栈“键”设置为“值”。
   * @memberOf Stack
   * @param {string} key 要设置的值的键。
   * @param {*} value 要设置的值。
   * @returns {Object} 返回堆栈缓存实例。
   */
  set(key, value) {
    let data = this.__data__
    if (data instanceof ListCache) {
      const pairs = data.__data__
      if (pairs.length < LARGE_ARRAY_SIZE - 1) {
        pairs.push([key, value])
        this.size = ++data.size
        return this
      }
      data = this.__data__ = new MapCache(pairs)
    }
    data.set(key, value)
    this.size = data.size
    return this
  }
}

export default Stack