-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnestedComments.js
More file actions
74 lines (61 loc) · 1.99 KB
/
Copy pathnestedComments.js
File metadata and controls
74 lines (61 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
export const countCommentItems = (arr, total = 0) => {
// arr.length && console.log("arr", arr)
const getCountForIdx = (arr, count = 0) => {
if (arr.length > 1) {
return countCommentItems(arr, count);
}
// console.log("arr", JSON.stringify(arr));
if (!arr[ 0 ]?.items?.length)
return count + 1;
return getCountForIdx(arr[ 0 ]?.items, count + 1);
};
if (!arr[ 0 ]) {
return total;
}
total = total + getCountForIdx([arr[ 0 ]]);
if (arr.length) {
total = total + countCommentItems(arr.slice(1));
}
return total;
};
export const limitNestedArray = (arr, limit) => {
let count = 0;
const customReducer = (accumulator, currentElement) => {
if (count === limit) {
// Break out early
return accumulator;
}
count = count + 1;
const newItem = { ...currentElement };
newItem.items = [];
if (currentElement.items && currentElement.items.length > 0) {
for (const nestedItem of currentElement.items) {
const temp = customReducer([], nestedItem);
const emptyArray = Array.isArray(temp) && !temp.length;
if (!emptyArray) newItem.items = [...newItem.items, temp];
}
}
return newItem;
};
const customReduce = (array, reducer) => {
// Exit early if limit = 0
if (limit === 0) {
return [];
}
let result = []; // start with an empty array
for (const element of array) {
result = [...result, reducer(result, element)];
// Check breaking condition
if (count === limit) {
break;
}
}
return result;
};
// Reverse the original array to get the most recent items
const reversedArray = arr.slice().reverse();
const truncatedReversedArray = customReduce(reversedArray, customReducer);
const truncatedArray = truncatedReversedArray.slice().reverse(); // restore the order
// console.log(JSON.stringify(truncatedArray, null, 2));
return truncatedArray;
};