Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { expect, it } from 'vitest';

import { generateFractionalIndexingKeyBetween } from '../../utils/fractional-indexing.js';

it('keeps keys ordered when inserting right after the first key', () => {
for (let i = 0; i < 100; i++) {
const keys = [generateFractionalIndexingKeyBetween(null, null)];
keys.unshift(generateFractionalIndexingKeyBetween(null, keys[0]));
for (let j = 0; j < 50; j++) {
const [a, b] = keys;
const key = generateFractionalIndexingKeyBetween(a, b);
expect(a < key && key < b, `${a} ${key} ${b}`).toBe(true);
keys.splice(1, 0, key);
}
}
});
7 changes: 6 additions & 1 deletion blocksuite/affine/shared/src/utils/fractional-indexing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ export function generateFractionalIndexingKeyBetween(
// generate a key between a and b
if (hasSamePrefix(aSubkey, bSubkey) && a !== null && b !== null) {
// conflict, if the subkeys are the same, generate a key between fullkeys
return generateKeyBetween(a, b) + '0' + postfix();
let key = generateKeyBetween(a, b);
// the postfix would sort the key after b if b continues with key + '0'
while (b.startsWith(key + '0')) {
key = generateKeyBetween(key, b);
}
return key + '0' + postfix();
} else {
return generateKeyBetween(aSubkey, bSubkey) + '0' + postfix();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,13 @@ test('edge cases', () => {
expect(d < b).toBeTruthy();
}
});

test('repeatedly inserting right after the first key', () => {
for (let i = 0; i < 100; i++) {
const keys = [generateFractionalIndexingKeyBetween(null, null)];
keys.unshift(gen(null, keys[0]));
for (let j = 0; j < 50; j++) {
keys.splice(1, 0, gen(keys[0], keys[1]));
}
}
});
7 changes: 6 additions & 1 deletion packages/common/infra/src/utils/fractional-indexing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ export function generateFractionalIndexingKeyBetween(
// generate a key between a and b
if (hasSamePrefix(aSubkey, bSubkey) && a !== null && b !== null) {
// conflict, if the subkeys are the same, generate a key between fullkeys
return generateKeyBetween(a, b) + '0' + postfix();
let key = generateKeyBetween(a, b);
// the postfix would sort the key after b if b continues with key + '0'
while (b.startsWith(key + '0')) {
key = generateKeyBetween(key, b);
}
return key + '0' + postfix();
} else {
return generateKeyBetween(aSubkey, bSubkey) + '0' + postfix();
}
Expand Down