Skip to content

Instantly share code, notes, and snippets.

@coderfin
Created July 29, 2016 17:43
Show Gist options
  • Save coderfin/999e6de42b185f7d9610521678685bb3 to your computer and use it in GitHub Desktop.
Save coderfin/999e6de42b185f7d9610521678685bb3 to your computer and use it in GitHub Desktop.
A set of Fibonacci methods using new features of ES2015 (ES6)
{
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