about summary refs log blame commit diff stats
path: root/qjs/fact.js
blob: c5d718e42b1c2c1053831bc94a8b85561ac3fb86 (plain) (tree)





































                                                                                   
import {assert} from "utils.js";


// https://sourceacademy.org/sicpjs/1.2.1#fig-1.6
// recursive 
function factorial_01(n) {
    return n === 1 
           ? 1
           : n * factorial_01(n - 1);
} 
assert(factorial_01(7) === 5040, 'factorial_01 returns an incorrect result.')
console.log(factorial_01(7), 'v01')


// https://sourceacademy.org/sicpjs/1.2.1#fig-1.8 
// iterative
function factorial_02(n) {
    return fact_iter(1, 1, n);
}
function fact_iter(product, counter, max_count) {
    return counter > max_count
           ? product
           : fact_iter(counter * product,
                       counter + 1,
                       max_count);
}
assert(factorial_02(7) === 5040, 'factorial_02 returns an incorrect result.')
console.log(factorial_02(7), 'v02')


// FROM SICP
// In contrasting iteration and recursion, we must be careful not to confuse the 
// notion of a recursive process with the notion of a recursive function. When we 
// describe a function as recursive, we are referring to the syntactic fact that 
// the function declaration refers (either directly or indirectly) to the function 
// itself. But when we describe a process as following a pattern that is, say, 
// linearly recursive, we are speaking about how the process evolves, not about 
// the syntax of how a function is written.