lodash源碼分析之緩存使用方式的進一步封裝

在世界上所有的民族之中,支配着他們的喜怒選擇的並不是天性,而是他們的觀點。

——盧梭《社會與契約論》

本文爲讀 lodash 源碼的第九篇,後續文章會更新到這個倉庫中,歡迎 star:pocket-lodash

gitbook也會同步倉庫的更新,gitbook地址:pocket-lodash

前言

在之前的《lodash源碼分析之Hash緩存》和《lodash源碼分析之List緩存》介紹過 lodash 的兩種緩存方式,在《lodash源碼分析之緩存方式的選擇》中介紹過這兩種緩存方式和 Map 的封裝,lodash 會根據緩存類型來選擇最優的緩存方式。

但是在 MapCache 類中,要初始化緩存和設置緩存都需要提供 keyvalue 組成的二維數組,因此在 SetCache 類中,lodash 提供了一種更方便的緩存設置方式,只需要提供緩存的值即可。

依賴

import MapCache from './MapCache.js'

lodash源碼分析之緩存方式的選擇

源碼分析

const HASH_UNDEFINED = '__lodash_hash_undefined__'

class SetCache {

  constructor(values) {
    let index = -1
    const length = values == null ? 0 : values.length

    this.__data__ = new MapCache
    while (++index < length) {
      this.add(values[index])
    }
  }

  add(value) {
    this.__data__.set(value, HASH_UNDEFINED)
    return this
  }

  has(value) {
    return this.__data__.has(value)
  }
}

SetCache.prototype.push = SetCache.prototype.add

總體思路

從源碼中可以看到,SetCache 其實調用的是 MapCache 類,使用緩存的值作爲 key ,所有的 key 對應的值都是 lodash 定義的標準 undefinedHASH_UNDEFINED ,正如之前文章中論述過的,這個值用於 Hash 緩存時,避免判斷是緩存是否存在時出錯。

判斷緩存是否存在,只需要判斷 MapCache 是否存在對應的 key

constructor

constructor(values) {
  let index = -1
  const length = values == null ? 0 : values.length

  this.__data__ = new MapCache
  while (++index < length) {
    this.add(values[index])
  }
}

這裏構造函數不需要再傳入 key-value 的二維數組了,只需要傳入包含所有緩存值的數組即可。

__data__ 屬性保存的其實是 MapCache 的實例。

初始化時只需要遍歷需要緩存的數組 values ,然後調用 add 方法,設置緩存即可。

add

add(value) {
  this.__data__.set(value, HASH_UNDEFINED)
  return this
}

add 方法用來設置緩存。

其實調用的是 MapCahce 實例的 set 方法,使用緩存值 value 作爲 key ,用 HASH_UNDEFINED 作爲緩存值。

### has

has(value) {
  return this.__data__.has(value)
}

has 方法用於判斷緩存是否存在。

只需要調用 MapCache 實例的 has 方法即可。

push

SetCache.prototype.push = SetCache.prototype.add

push 方法只是 add 方法的別名。

License

署名-非商業性使用-禁止演繹 4.0 國際 (CC BY-NC-ND 4.0)

最後,所有文章都會同步發送到微信公衆號上,歡迎關注,歡迎提意見:

作者:對角另一面

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章