Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var commentsTree = [
- {
- id: 1,
- text: 'Some lorem',
- comments: [
- {
- id: 2,
- text: 'Another lorem',
- comments: [
- {
- id: 3,
- text: 'Third lorem',
- comments: [
- {
- id: 11,
- text: 'Hello'
- },
- {
- id: 12,
- text: 'Bye'
- }
- ]
- },
- ]
- },
- {
- id: 9,
- text: 'True'
- }
- ]
- },
- {
- id: 4,
- text: 'Functional programming',
- comments: [
- {
- id: 5,
- text: 'Yes'
- },
- {
- id: 6,
- text: 'No'
- }
- ]
- }
- ];
- var countCommentsES5 = function(comments) {
- return comments.reduce(function(count, comment) {
- if (comment.comments) {
- return count + 1 + countCommentsES5(comment.comments);
- } else {
- return count + 1;
- }
- }, 0);
- };
- var countCommentsES6 = comments => {
- return comments.reduce(
- (count, comment) => (
- comment.comments
- ? count + 1 + countCommentsES6(comment.comments)
- : count + 1
- ),
- 0
- )
- }
- console.log(countCommentsES5(commentsTree));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement