In: Computer Science
Javascript problem:
Given an argument of a list of book objects:
Example test case input:
{
"title" : "Book A",
"pages": "50",
"next": {
"title": "Book B",
"pages": 20,
"next": null
}
}
create a recursive function to return the total number total # of pages read in the list. If there are no books in the list, return 0.
Here is code:
function countPages(book) {
if (book.next === null) {
return 0;
}
return Number(book.pages) + countPages(book.next);
}
Sample code to test:
function countPages(book) {
if (book.next === null) {
return 0;
}
return Number(book.pages) + countPages(book.next);
}
let books = {
"title": "Book A",
"pages": "50",
"next": {
"title": "Book B",
"pages": 20,
"next": null
}
}
console.log(countPages(books));
Output: