Created
July 29, 2016 17:43
-
-
Save coderfin/999e6de42b185f7d9610521678685bb3 to your computer and use it in GitHub Desktop.
A set of Fibonacci methods using new features of ES2015 (ES6)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
class Fibonacci { | |
static *inRange(start, end) { | |
for(let num of Fibonacci) { | |
if(num >= start && num <= end) { | |
yield num; | |
} else if(num > end) { | |
break; | |
} | |
} | |
}; | |
static *getNNumbers(n = 0, start = 0, end = Number.MAX_SAFE_INTEGER) { | |
let count = 0; | |
for(let num of Fibonacci.inRange(start, end)) { | |
if(count < n) { | |
yield num; | |
} | |
count++; | |
} | |
}; | |
static [Symbol.iterator]() { | |
let previous = 0; | |
let current = 1; | |
let first = true; | |
let second = true; | |
return { | |
next () { | |
if(first) { | |
current = 0; | |
first = false; | |
} else if (second) { | |
current = 1; | |
second = false; | |
} else { | |
[previous, current] = [current, previous + current]; | |
} | |
return { | |
done: false, | |
value: current | |
}; | |
} | |
} | |
}; | |
}; | |
let nums = [...Fibonacci.inRange(0, 100)]; | |
console.log(nums); | |
nums = [...Fibonacci.getNNumbers(21)]; | |
console.log(nums); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment