Now lets say we want a function to get the sum of all

This preview shows page 7 - 10 out of 14 pages.

Now let’s say we want a function to get the sum of all salaries. How can we do that? An iterative approach is not easy, because the structure is not simple. The first idea may be to make a for loop over company with nested subloop over 1st level departments. But then we need more nested subloops to iterate over the staff in 2nd level departments like sites … And then another subloop inside those for 3rd level departments that might appear in the future? If we put 3-4 nested subloops in the code to traverse a single object, it becomes rather ugly. Let’s try recursion. As we can see, when our function gets a department to sum, there are two possible cases: 1. Either it’s a “simple” department with an array of people – then we can sum the salaries in a simple loop. 2. Or it’s an object with N subdepartments – then we can make N recursive calls to get the sum for each of the subdeps and combine the results. The 1st case is the base of recursion, the trivial case, when we get an array. The 2nd case when we gen an object is the recursive step. A complex task is split into subtasks for smaller departments. They may in turn split again, but sooner or later the split will finish at (1). The algorithm is probably even easier to read from the code:
Image of page 7

Subscribe to view the full document.

let company = { // the same object, compressed for brevity sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 600 }], development: { sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }], internals: [{name: 'Jack', salary: 1300}] } }; // The function to do the job function sumSalaries(department) { if (Array.isArray(department)) { // case (1) return department.reduce((prev, current) => prev + current.salary, 0); // sum the array } else { // case (2) let sum = 0; for (let subdep of Object.values(department)) { sum += sumSalaries(subdep); // recursively call for subdepartments, sum the results } return sum; } } alert(sumSalaries(company)); // 6700 The code is short and easy to understand (hopefully?). That’s the power of recursion. It also works for any level of subdepartment nesting. Here’s the diagram of calls: We can easily see the principle: for an object {...} subcalls are made, while arrays [...] are the “leaves” of the recursion tree, they give immediate result. Note that the code uses smart features that we’ve covered before: Method arr.reduce explained in the chapter Array methods to get the sum of the array.
Image of page 8
Loop for(val of Object.values(obj)) to iterate over object values: Object.values returns an array of them. Recursive structures A recursive (recursively-defined) data structure is a structure that replicates itself in parts. We’ve just seen it in the example of a company structure above. A company department is: Either an array of people. Or an object with departments . For web-developers there are much better-known examples: HTML and XML documents.
Image of page 9

Subscribe to view the full document.

Image of page 10

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern