Skip to content

linkdd/arecursion-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Asynchronous Recursion without Maximum Depth

⚗️ How does it work ?

Thanks to the setImmediate function, the next iteration of the recursion is scheduled on the next frame of the event-loop.

The current iteration will return, removing the function from the call stack.

The whole recursion is wrapped in a promise that will resolve to the result of your recursive function

📦 Installation

$ yarn add arecursion-js

🔧 Usage

const recursion = require('arecursion-js')

const factorial = recursion.doAsync((n, acc) => {
    if (typeof acc === 'undefined') {
        acc = 1
    }

    if (n > 1) {
        return recursion.iterate(n - 1, acc * n)
    }
    else {
        return recursion.end(acc)
    }
})

const main = async () => {
    console.log(await factorial(5))
}

main()

Or with an asynchronous function:

const recursion = require('arecursion-js')

const slow_sum = recursion.doAsync(async (n, acc) => {
    if (typeof acc === 'undefined') {
        acc = 0
    }

    await some_slow_task()

    if (n > 1) {
        return recursion.iterate(n - 1, acc + n)
    }
    else {
        return recursion.end(acc)
    }
})

const main = async () => {
    console.log(await slow_sum(5))
}

main()

📝 License

This package is released under the terms of the MIT License.

About

Asynchronous recursion without maximum depth

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •