Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. var commentsTree = [
  2. {
  3. id: 1,
  4. text: 'Some lorem',
  5. comments: [
  6. {
  7. id: 2,
  8. text: 'Another lorem',
  9. comments: [
  10. {
  11. id: 3,
  12. text: 'Third lorem',
  13. comments: [
  14. {
  15. id: 11,
  16. text: 'Hello'
  17. },
  18. {
  19. id: 12,
  20. text: 'Bye'
  21. }
  22. ]
  23. },
  24. ]
  25. },
  26. {
  27. id: 9,
  28. text: 'True'
  29. }
  30. ]
  31. },
  32. {
  33. id: 4,
  34. text: 'Functional programming',
  35. comments: [
  36. {
  37. id: 5,
  38. text: 'Yes'
  39. },
  40. {
  41. id: 6,
  42. text: 'No'
  43. }
  44. ]
  45. }
  46. ];
  47.  
  48. var countCommentsES5 = function(comments) {
  49. return comments.reduce(function(count, comment) {
  50. if (comment.comments) {
  51. return count + 1 + countCommentsES5(comment.comments);
  52. } else {
  53. return count + 1;
  54. }
  55. }, 0);
  56. };
  57.  
  58. var countCommentsES6 = comments => {
  59. return comments.reduce(
  60. (count, comment) => (
  61. comment.comments
  62. ? count + 1 + countCommentsES6(comment.comments)
  63. : count + 1
  64. ),
  65. 0
  66. )
  67. }
  68.  
  69. console.log(countCommentsES5(commentsTree));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement