Y
Y
yuriytkachenko2019-09-19 23:10:09
JavaScript
yuriytkachenko, 2019-09-19 23:10:09

An even simpler and more practical example of recursion?

Recursion example:
implement the formula xn= x*xn-1

function power(x,n){
  if(n == 1) {
     return x;
  }
  else {
     return x*power(x,n-1);
}
  }
console.log(power(2,3));

But the example for me personally is a little complicated and it is unlikely that this formula is often used when creating sites.
Can you give an example that is simpler and that could really be used when creating a site?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Kulaxyz, 2019-09-19
@yuriytkachenko

Let me give you an example that I used the other day. Unfortunately, not in JS, but in PHP, and it is not so simple, but maybe it will help you a little:

public function post()
    {
        if (!$this->parent()) {
            return  $this->commentable_id;
        }
        else {
            return $this->parent()->post();
        }
    }

In general, the essence is such that it was necessary to notify the user if someone commented on his post, while the site has a multi-level comment system. And if someone wrote a response to a comment, then it is no longer connected with the post, but the author still needs to be notified. If the comment is written not as a response to someone else, but as just a comment under the post itself, then its parent will return null, otherwise it will return the comment to which it is the answer. And with the help of recursion, I implemented getting the id of the post on which someone left a comment: at the moment of creating a comment, this post method (a function, if it’s clearer) is called, which, if this is a first-level comment, will return the post id, and if not, then it will call the same method, but already at the comment, the answer to which is this one. And this function will be called any number of times,

M
McBernar, 2019-09-20
@McBernar

Recursion is great if you need to render the DOM from a tree dataset.
I once made a widget that is embedded on sites. In order not to make an iframe (as it was necessary) and not to write tons of the same createElement and appendChild, you simply feed the config function in JSON, and it parses it and renders the elements.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question