Skip to content

Instantly share code, notes, and snippets.

@bvaughn
Last active September 2, 2017 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bvaughn/8835fe4a5aac7cea43d787bc9e81800c to your computer and use it in GitHub Desktop.
Save bvaughn/8835fe4a5aac7cea43d787bc9e81800c to your computer and use it in GitHub Desktop.
Proof of concept cellKeyGetter implementation for Grid (react-virtualized 9.10+)
function createLittleKeyPool() {
const availableKeys = [];
const inUseKeys = [];
let previousCycle = null;
let keyCounter = 0;
function releaseKeys({ startIndex, stopIndex }) {
if (previousCycle !== null) {
const {
startIndex: prevStartIndex,
stopIndex: prevStopIndex
} = previousCycle;
let targetIndex = Math.min(prevStopIndex + 1, startIndex);
for (let i = prevStartIndex; i < targetIndex; i++) {
const key = inUseKeys[i];
delete inUseKeys[i];
if (key != null) {
availableKeys.push(key);
}
}
targetIndex = Math.max(prevStartIndex - 1, stopIndex);
for (let i = prevStopIndex; i > stopIndex; i--) {
const key = inUseKeys[i];
delete inUseKeys[i];
if (key != null) {
availableKeys.push(key);
}
}
}
previousCycle = { startIndex, stopIndex };
}
function getKey(index) {
let key;
if (inUseKeys.hasOwnProperty(index)) {
key = inUseKeys[index];
} else if (availableKeys.length > 0) {
key = availableKeys.pop();
} else {
key = keyCounter++;
}
inUseKeys[index] = key;
return key;
}
return { releaseKeys, getKey };
}
function createKeyPool() {
const x = createLittleKeyPool();
const y = createLittleKeyPool();
function onSectionRendered({
columnOverscanStartIndex,
columnOverscanStopIndex,
rowOverscanStartIndex,
rowOverscanStopIndex
}) {
x.releaseKeys({
startIndex: columnOverscanStartIndex,
stopIndex: columnOverscanStopIndex
});
y.releaseKeys({
startIndex: rowOverscanStartIndex,
stopIndex: rowOverscanStopIndex
});
}
function cellKeyGetter({columnIndex, rowIndex}) {
return `${y.getKey(rowIndex)}-${x.getKey(columnIndex)}`;
}
return {
cellKeyGetter,
onSectionRendered
};
}
const {cellKeyGetter, onSectionRendered} = createKeyPool();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment