Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: replace binarySearchByDateEqualOrNearestGreater with findIndexInSortedArray \w midpoint match #1370

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
45 changes: 13 additions & 32 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,12 +310,18 @@ export function formatMessage<StreamChatGenerics extends ExtendableGenerics = De

export const findIndexInSortedArray = <T, L>({
needle,
returnOnMidMatch,
sortedArray,
selectValueToCompare = (e) => e,
sortDirection = 'ascending',
}: {
needle: T;
sortedArray: readonly T[];
/**
* Returns the index of the midpoint if it matches the target value.
* Should be enabled only if the searched array cannot contain duplicates.
*/
returnOnMidMatch?: boolean;
/**
* In array of objects (like messages), pick a specific
* property to compare needle value to.
Expand Down Expand Up @@ -353,7 +359,7 @@ export const findIndexInSortedArray = <T, L>({

const comparableMiddle = selectValueToCompare(sortedArray[middle]);

// if (comparableNeedle === comparableMiddle) return middle;
if (returnOnMidMatch && comparableNeedle === comparableMiddle) return middle;

if (
(sortDirection === 'ascending' && comparableNeedle < comparableMiddle) ||
Expand Down Expand Up @@ -499,36 +505,6 @@ type MessagePaginationUpdatedParams<StreamChatGenerics extends ExtendableGeneric
messagePaginationOptions?: MessagePaginationOptions;
};

export function binarySearchByDateEqualOrNearestGreater(
array: {
created_at?: string;
}[],
targetDate: Date,
): number {
let left = 0;
let right = array.length - 1;

while (left <= right) {
const mid = Math.floor((left + right) / 2);
const midCreatedAt = array[mid].created_at;
if (!midCreatedAt) {
left += 1;
continue;
}
const midDate = new Date(midCreatedAt);

if (midDate.getTime() === targetDate.getTime()) {
return mid;
} else if (midDate.getTime() < targetDate.getTime()) {
left = mid + 1;
} else {
right = mid - 1;
}
}

return left;
}

const messagePaginationCreatedAtAround = <StreamChatGenerics extends ExtendableGenerics = DefaultGenerics>({
parentSet,
requestedPageSize,
Expand Down Expand Up @@ -580,7 +556,12 @@ const messagePaginationCreatedAtAround = <StreamChatGenerics extends ExtendableG
updateHasPrev = firstPageMsgIsFirstInSet;
updateHasNext = lastPageMsgIsLastInSet;
const midPointByCount = Math.floor(returnedPage.length / 2);
const midPointByCreationDate = binarySearchByDateEqualOrNearestGreater(returnedPage, createdAtAroundDate);
const midPointByCreationDate = findIndexInSortedArray<{ created_at: Date }, number>({
needle: { created_at: createdAtAroundDate },
sortedArray: returnedPage.map(formatMessage),
sortDirection: 'ascending',
selectValueToCompare: (message) => message.created_at.getTime(),
});

if (midPointByCreationDate !== -1) {
hasPrev = midPointByCount <= midPointByCreationDate;
Expand Down
6 changes: 5 additions & 1 deletion test/unit/channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -1275,9 +1275,13 @@ describe('Channel.query', async () => {
it('should update pagination for queried message set to prevent more pagination', async () => {
const client = await getClientWithUser();
const channel = client.channel('messaging', uuidv4());
const timestamp = new Date('2024-01-01T00:00:00.000Z').getTime();

const mockedChannelQueryResponse = {
...mockChannelQueryResponse,
messages: Array.from({ length: DEFAULT_QUERY_CHANNEL_MESSAGE_LIST_PAGE_SIZE - 1 }, generateMsg),
messages: Array.from({ length: DEFAULT_QUERY_CHANNEL_MESSAGE_LIST_PAGE_SIZE - 1 }, (_, index) =>
generateMsg({ created_at: new Date(timestamp + index * 1000).toISOString() }),
),
};
const mock = sinon.mock(client);
mock.expects('post').returns(Promise.resolve(mockedChannelQueryResponse));
Expand Down
138 changes: 105 additions & 33 deletions test/unit/channel_state.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,21 +97,39 @@ describe('ChannelState addMessagesSorted', function () {

it('add a message with same created_at', async function () {
const state = new ChannelState();

for (let i = 0; i < 10; i++) {
state.addMessagesSorted([generateMsg({ id: `${i}`, date: `2020-01-01T00:00:00.00${i}Z` })]);
const pairCount = 10;
const msgCount = pairCount * 2;

for (let i = 0; i < msgCount; i += 2) {
state.addMessagesSorted([
generateMsg({ id: `${i}`, date: `2020-01-01T00:00:00.0${i.toString().padStart(2, '0')}Z` }),
generateMsg({ id: `${i + 1}`, date: `2020-01-01T00:00:00.0${i.toString().padStart(2, '0')}Z` }),
]);
}

for (let i = 10; i < state.messages.length - 1; i++) {
for (let j = i + 1; i < state.messages.length - 1; j++)
expect(state.messages[i].created_at.getTime()).to.be.lessThan(state.messages[j].created_at.getTime());
for (let i = 0; i < msgCount; i += 2) {
expect(state.messages[i].created_at.getTime()).to.be.eq(state.messages[i + 1].created_at.getTime());
if (i + 2 < msgCount) {
expect(state.messages[i].created_at.getTime()).to.be.lessThan(
state.messages[i + 2].created_at.getTime(),
);
}
}

expect(state.messages).to.have.length(10);
state.addMessagesSorted([generateMsg({ id: 'id', date: `2020-01-01T00:00:00.007Z` })]);
expect(state.messages).to.have.length(11);
expect(state.messages[7].id).to.be.equal('7');
expect(state.messages[8].id).to.be.equal('id');
expect(state.messages).to.have.length(msgCount);
state.addMessagesSorted([generateMsg({ id: '1stAdded', date: `2020-01-01T00:00:00.014Z` })]);

expect(state.messages).to.have.length(msgCount + 1);
expect(state.messages[14].id).to.be.equal('14');
expect(state.messages[15].id).to.be.equal('15');
expect(state.messages[16].id).to.be.equal('1stAdded');
state.addMessagesSorted([generateMsg({ id: '2ndAdded', date: `2020-01-01T00:00:00.014Z` })]);

expect(state.messages).to.have.length(msgCount + 2);
expect(state.messages[14].id).to.be.equal('14');
expect(state.messages[15].id).to.be.equal('15');
expect(state.messages[16].id).to.be.equal('1stAdded');
expect(state.messages[17].id).to.be.equal('2ndAdded');
});

it('add lots of messages in order', async function () {
Expand Down Expand Up @@ -208,8 +226,22 @@ describe('ChannelState addMessagesSorted', function () {

it('should add messages to new message set', () => {
const state = new ChannelState();
state.addMessagesSorted([generateMsg({ id: '12' }), generateMsg({ id: '13' }), generateMsg({ id: '14' })]);
state.addMessagesSorted([generateMsg({ id: '0' }), generateMsg({ id: '1' })], false, false, true, 'new');

state.addMessagesSorted([
generateMsg({ id: '12', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '13', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '14', created_at: '2020-01-01T00:00:00.003Z' }),
]);
state.addMessagesSorted(
[
generateMsg({ id: '0', created_at: '2020-01-01T00:00:00.004Z' }),
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.005Z' }),
],
false,
false,
true,
'new',
);

expect(state.messages.length).to.be.equal(3);
expect(state.messages[0].id).to.be.equal('12');
Expand All @@ -223,7 +255,11 @@ describe('ChannelState addMessagesSorted', function () {
it('should add messages to current message set', () => {
const state = new ChannelState();
state.addMessagesSorted(
[generateMsg({ id: '12' }), generateMsg({ id: '13' }), generateMsg({ id: '14' })],
[
generateMsg({ id: '12', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '13', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '14', created_at: '2020-01-01T00:00:00.003Z' }),
],
false,
false,
true,
Expand All @@ -239,7 +275,11 @@ describe('ChannelState addMessagesSorted', function () {
it('should add messages to latest message set', () => {
const state = new ChannelState();
state.addMessagesSorted(
[generateMsg({ id: '12' }), generateMsg({ id: '13' }), generateMsg({ id: '14' })],
[
generateMsg({ id: '12', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '13', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '14', created_at: '2020-01-01T00:00:00.003Z' }),
],
false,
false,
true,
Expand All @@ -258,17 +298,37 @@ describe('ChannelState addMessagesSorted', function () {

it(`should add messages to latest message set when it's not currently active`, () => {
const state = new ChannelState();

state.addMessagesSorted(
[generateMsg({ id: '12' }), generateMsg({ id: '13' }), generateMsg({ id: '14' })],
[
generateMsg({ id: '12', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '13', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '14', created_at: '2020-01-01T00:00:00.003Z' }),
],
false,
false,
true,
'latest',
);
state.addMessagesSorted([generateMsg({ id: '0' }), generateMsg({ id: '1' })], false, false, true, 'new');
state.addMessagesSorted(
[
generateMsg({ id: '0', created_at: '2020-01-01T00:00:00.004Z' }),
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.005Z' }),
],
false,
false,
true,
'new',
);
state.messageSets[0].isCurrent = false;
state.messageSets[1].isCurrent = true;
state.addMessagesSorted([generateMsg({ id: '15' })], false, false, true, 'latest');
state.addMessagesSorted(
[generateMsg({ id: '15', created_at: '2020-01-01T00:00:00.006Z' })],
false,
false,
true,
'latest',
);

expect(state.latestMessages.length).to.be.equal(4);
expect(state.latestMessages[3].id).to.be.equal('15');
Expand Down Expand Up @@ -684,10 +744,10 @@ describe('deleteUserMessages', () => {
const user1 = generateUser();
const user2 = generateUser();

const m1u1 = generateMsg({ user: user1 });
const m2u1 = generateMsg({ user: user1 });
const m1u2 = generateMsg({ user: user2 });
const m2u2 = generateMsg({ user: user2 });
const m1u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.001Z' });
const m2u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.002Z' });
const m1u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.003Z' });
const m2u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.004Z' });

state.addMessagesSorted([m1u1, m2u1, m1u2, m2u2]);

Expand Down Expand Up @@ -719,10 +779,10 @@ describe('deleteUserMessages', () => {
const user1 = generateUser();
const user2 = generateUser();

const m1u1 = generateMsg({ user: user1 });
const m2u1 = generateMsg({ user: user1 });
const m1u2 = generateMsg({ user: user2 });
const m2u2 = generateMsg({ user: user2 });
const m1u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.001Z' });
const m2u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.002Z' });
const m1u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.003Z' });
const m2u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.004Z' });

state.addMessagesSorted([m1u1, m2u1, m1u2, m2u2]);
expect(state.messages).to.have.length(4);
Expand Down Expand Up @@ -755,10 +815,10 @@ describe('updateUserMessages', () => {
let user1 = generateUser();
const user2 = generateUser();

const m1u1 = generateMsg({ user: user1 });
const m2u1 = generateMsg({ user: user1 });
const m1u2 = generateMsg({ user: user2 });
const m2u2 = generateMsg({ user: user2 });
const m1u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.001Z' });
const m2u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.002Z' });
const m1u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.003Z' });
const m2u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.004Z' });

state.addMessagesSorted([m1u1, m2u1, m1u2, m2u2]);

Expand All @@ -785,7 +845,11 @@ describe('updateUserMessages', () => {
describe('latestMessages', () => {
it('should return latest messages - if they are the current message set', () => {
const state = new ChannelState();
const messages = [generateMsg({ id: '1' }), generateMsg({ id: '2' }), generateMsg({ id: '3' })];
const messages = [
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '2', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '3', created_at: '2020-01-01T00:00:00.003Z' }),
];
state.addMessagesSorted(messages);

expect(state.latestMessages.length).to.be.equal(messages.length);
Expand All @@ -796,7 +860,11 @@ describe('latestMessages', () => {

it('should return latest messages - if they are not the current message set', () => {
const state = new ChannelState();
const latestMessages = [generateMsg({ id: '1' }), generateMsg({ id: '2' }), generateMsg({ id: '3' })];
const latestMessages = [
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '2', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '3', created_at: '2020-01-01T00:00:00.003Z' }),
];
state.addMessagesSorted(latestMessages);
const newMessages = [generateMsg({ id: '0' })];
state.addMessagesSorted(newMessages, false, true, true, 'new');
Expand All @@ -811,7 +879,11 @@ describe('latestMessages', () => {

it('should return latest messages - if they are not the current message set and new messages received', () => {
const state = new ChannelState();
const latestMessages = [generateMsg({ id: '1' }), generateMsg({ id: '2' }), generateMsg({ id: '3' })];
const latestMessages = [
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '2', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '3', created_at: '2020-01-01T00:00:00.003Z' }),
];
state.addMessagesSorted(latestMessages);
const newMessages = [generateMsg({ id: '0' })];
state.addMessagesSorted(newMessages, false, true, true, 'new');
Expand Down
20 changes: 0 additions & 20 deletions test/unit/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2690,23 +2690,3 @@ describe('messageSetPagination', () => {
});
});
});

describe('', () => {
const messages = [
{ created_at: '2024-08-05T08:55:00.199808Z', id: '0' },
{ created_at: '2024-08-05T08:55:01.199808Z', id: '1' },
{ created_at: '2024-08-05T08:55:02.199808Z', id: '2' },
{ created_at: '2024-08-05T08:55:03.199808Z', id: '3' },
{ created_at: '2024-08-05T08:55:04.199808Z', id: '4' },
{ created_at: '2024-08-05T08:55:05.199808Z', id: '5' },
{ created_at: '2024-08-05T08:55:06.199808Z', id: '6' },
{ created_at: '2024-08-05T08:55:07.199808Z', id: '7' },
{ created_at: '2024-08-05T08:55:08.199808Z', id: '8' },
];
it('finds the nearest newer item', () => {
expect(binarySearchByDateEqualOrNearestGreater(messages, new Date('2024-08-05T08:55:02.299808Z'))).to.eql(3);
});
it('finds the nearest matching item', () => {
expect(binarySearchByDateEqualOrNearestGreater(messages, new Date('2024-08-05T08:55:07.199808Z'))).to.eql(7);
});
});
Comment on lines -2694 to -2712
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved to utils.test.ts with additions.

Loading
Loading