aboutsummaryrefslogtreecommitdiff
path: root/entries/perryliao/fib.groovy
blob: d625d6814d6255cac0288d5cc81fb129b4bd56ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
pipeline {
    agent any

    parameters {
        string defaultValue: '2', description: 'Number to compute in the Fibonacci Sequence', name: 'num', trim: true
    }

    stages {
        stage('Validate Parameter') {
            steps {
                script {
                    assert params.num.isInteger()
                }
            }
        }
        stage('Create Cache') {
            steps {
                script {
                    if (!fileExists("fibCache")) {
                        sh 'echo "0\n1" > fibCache'
                    }
                }
            }
        }
        stage('Get Fibbonacci') {
            steps {
                script {
                    nComputed = sh(returnStdout: true, script: "wc -l < fibCache").trim().toInteger()
                    result = fib(params.num.toInteger())
                    println("The result is F(${params.num}) = ${result}")
                }
            }
        }
    }
}

def nComputed

int fib(int n, cache = 'fibCache') {
    if (n >= nComputed) {
        // Need to do more recursion
        result = fib(n - 2, cache) + fib(n - 1, cache)
        nComputed++
        sh "echo '${result}' >> ${cache}"
        return result
    } else {
        // Already have what we need, so read from cache
        return sh(returnStdout: true, script: "sed -n '${n + 1}p' ${cache}").toInteger()
    }
}