cache as argument to read (#13865)
/*** Copyright (c) 2014-present, Facebook, Inc.** This source code is licensed under the MIT license found in the* LICENSE file in the root directory of this source tree.** @flow*/import {unstable_scheduleCallback as scheduleCallback} from 'scheduler';type Entry<T> = {|value: T,onDelete: () => mixed,previous: Entry<T>,next: Entry<T>,|};export function createLRU<T>(limit: number) {let LIMIT = limit;// Circular, doubly-linked listlet first: Entry<T> | null = null;let size: number = 0;let cleanUpIsScheduled: boolean = false;function scheduleCleanUp() {if (cleanUpIsScheduled === false && size > LIMIT) {// The cache size exceeds the limit. Schedule a callback to delete the// least recently used entries.cleanUpIsScheduled = true;scheduleCallback(cleanUp);}}function cleanUp() {cleanUpIsScheduled = false;deleteLeastRecentlyUsedEntries(LIMIT);}function deleteLeastRecentlyUsedEntries(targetSize: number) {// Delete entries from the cache, starting from the end of the list.if (first !== null) {const resolvedFirst: Entry<T> = (first: any);let last = resolvedFirst.previous;while (size > targetSize && last !== null) {const onDelete = last.onDelete;const previous = last.previous;last.onDelete = (null: any);// Remove from the listlast.previous = last.next = (null: any);if (last === first) {// Reached the head of the list.first = last = null;} else {(first: any).previous = previous;previous.next = (first: any);last = previous;}size -= 1;// Call the destroy method after removing the entry from the list. If it// throws, the rest of cache will not be deleted, but it will be in a// valid state.onDelete();}}}function add(value: T, onDelete: () => mixed): Entry<T> {const entry = {value,onDelete,next: (null: any),previous: (null: any),};if (first === null) {entry.previous = entry.next = entry;first = entry;} else {// Append to headconst last = first.previous;last.next = entry;entry.previous = last;first.previous = entry;entry.next = first;first = entry;}size += 1;return entry;}function update(entry: Entry<T>, newValue: T): void {entry.value = newValue;}function access(entry: Entry<T>): T {const next = entry.next;if (next !== null) {// Entry already cachedconst resolvedFirst: Entry<T> = (first: any);if (first !== entry) {// Remove from current positionconst previous = entry.previous;previous.next = next;next.previous = previous;// Append to headconst last = resolvedFirst.previous;last.next = entry;entry.previous = last;resolvedFirst.previous = entry;entry.next = resolvedFirst;first = entry;}} else {// Cannot access a deleted entry// TODO: Error? Warning?}scheduleCleanUp();return entry.value;}function setLimit(newLimit: number) {LIMIT = newLimit;scheduleCleanUp();}return {add,update,access,setLimit,};}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。