场景
2023年06月17日
一、数组扁平
function* flat(array) {
for (let item of array) {
if (Array.isArray(item)) {
yield* flat(item);
} else {
yield item;
}
}
}
const array = [1, [2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, 13, 14]]]]];
const result = [...flat(array)];
console.log(result); // 结果: // 结果: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
二、斐波那契数列
2.1 N 位斐波那契数列
function* fibonacci() {
let [prev, curr] = [0, 1];
for (;;) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}
function getFib(n) {
const reuslt = [];
for (let value of fibonacci()) {
if (reuslt.length >= n) {
return reuslt;
}
reuslt.push(value);
}
}
const fib = getFib(10);
console.log(fib);
2.2 斐波那契数列第 N 位
function* fibonacci() {
let [prev, curr] = [0, 1];
for (;;) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}
function getFibByN(n) {
let index = 1;
for (let value of fibonacci()) {
if (index >= n) {
return value;
}
index++;
}
}
const fibN = getFibByN(10);
console.log(fibN);