Skip to content

Instantly share code, notes, and snippets.

@RayLuxembourg
Created April 28, 2019 15:11
Show Gist options
  • Save RayLuxembourg/69f59c9e17041602ae07516c02ea56fd to your computer and use it in GitHub Desktop.
Save RayLuxembourg/69f59c9e17041602ae07516c02ea56fd to your computer and use it in GitHub Desktop.
Fib Algorithm practice
const fibForLoop = (position: number) => {
const result = [0, 1]
for (let i = 2; i <= position; i++) {
const a = result[i - 1] // first iteration will return 0 , next 1 , 2 , 3
const b = result[i - 2] // first iteration will return 1 , next 2 , 3 , 5}
result.push(a + b)
}
return result[position]
}
const t0 = performance.now()
const res = fibForLoop(1)
const t1 = performance.now()
console.log(`Took`, (t1 - t0), 'milliseconds to generate:', res)
const fibRecursive = (pos: number) => {
const arr: number[] = []
const fn = (position: number) => {
if (arr[position]) return arr[position]
if (position < 2) {
arr[position] = position
} else {
arr[position] = fn(position - 1) + fn(position - 2)
}
return arr[position]
}
return fn(pos)
}
const t2 = performance.now()
const res1 = fibRecursive(10)
const t3= performance.now()
console.log(`Took`, (t1 - t0), 'milliseconds to generate:', res1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment