Skip to content

Commit

Permalink
Sort tree topic posts clientside
Browse files Browse the repository at this point in the history
  • Loading branch information
danon committed Nov 27, 2024
1 parent 7946d44 commit ba9b011
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 15 deletions.
11 changes: 1 addition & 10 deletions resources/js/store/modules/posts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,7 @@ const mutations = {
state = Object.assign(state, pagination);
},

add(state, post: Post) {
if (isModeTree(state)) {
if (post.tree_parent_post_id) {
const parentIndex = state.data.findIndex(otherPost => otherPost.id === post.tree_parent_post_id);
if (parentIndex > -1) {
state.data.splice(parentIndex + 1, 0, post);
return;
}
}
}
add(state, post: Post): void {
state.data[post.id!] = post;
},

Expand Down
26 changes: 24 additions & 2 deletions resources/js/treeTopic/postOrdering.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {TreeList} from "./treeList";
import {Post} from "../types/models";
import {TreeList} from "./treeList";

export type PostOrdering = 'orderByCreationDate' | 'orderByLikes';

export function postsOrdered(posts: Post[], ordering: PostOrdering): Post[] {
const tree = new TreeList<Post>((a, b) => 0);
const tree = new TreeList<Post>(postOrdering(ordering));
for (const post of posts) {
if (!post.tree_parent_post_id) {
tree.add(post.id, post);
Expand All @@ -19,3 +19,25 @@ export function postsOrdered(posts: Post[], ordering: PostOrdering): Post[] {
}
return orderedPosts;
}

function postOrdering(ordering: PostOrdering): (a, b) => number {
if (ordering === 'orderByCreationDate') {
return orderByCreationDateAsc;
}
return orderByScoreThenCreationDate;
}

function orderByScoreThenCreationDate(a: Post, b: Post): number {
if (a.score === b.score) {
return orderByCreationDateAsc(a, b);
}
return orderByScoreDesc(a, b);
}

function orderByScoreDesc(a: Post, b: Post): number {
return b.score - a.score;
}

function orderByCreationDateAsc(a: Post, b: Post): number {
return a.created_at! > b.created_at! ? 1 : -1;
}
5 changes: 2 additions & 3 deletions resources/js/treeTopic/treeList.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

interface Record<T> {
id: number;
parentId: number | null;
Expand Down Expand Up @@ -47,8 +46,8 @@ export class TreeList<T> {
for (const record of records) {
list.push(record);
if (record.children.length > 0) {
const children = record.children.sort(this.recordSorter.bind(this));
list.push(...this.flattened(children));
record.children.sort(this.recordSorter.bind(this));
list.push(...this.flattened(record.children));
}
}
return list;
Expand Down

0 comments on commit ba9b011

Please sign in to comment.