function generateOdds(len) { let odd = 1; let arr = []; for (let i = 1; i <= len; i++){ arr.push(odd); odd += 2; } return arr; } My function works with loops.
function generateOdds(len) { let odd = 1; let arr = []; for (let i = 1; i <= len; i++){ arr.push(odd); odd += 2; } return arr; } My function works with loops.
Without iterations, it will not work at all, one way or another, you will have to set N values in the array.
But there are ways to hide the loop by invoking one of the native array iteration methods that can be created using the Array(length) constructor.
function odds(n) { let res = new Array(n).fill(0); res.forEach((_, i, arr) => arr[i] = 2*i+1); return res; } console.info(odds(8)); function odds(n) { return new Array(n).fill(0) .map((_, i) => 2*i+1); } console.info(odds(8)); function odds(n) { return new Array(n).fill(0) .reduce((carry, _) => (carry.push(carry.length*2+1), carry), []); } console.info(odds(8)); You can also use generators :
However, even without iterations
function nOdds(n) { var i = 0; return function*() { while (i < n) { yield 2*i+1; ++i; } }; } console.log([...nOdds(8)()]) You can also turn any cycle into recursion:
function nOdds(n) { if (n == 0) return []; let res = nOdds(n-1); res.push(2*n - 1); return res; } function nOdds2(n) { if (n == 0) return []; return nOdds2(n-1).concat([2*n - 1]); } // (c) Grundy function* genNOdds(len){ if(len==1) return yield 1; yield *genNOdds(len-1); yield 2*len-1; } console.log(nOdds(3)); console.log(nOdds2(3)); console.log([...genNOdds(5)]) Array#map iterates in the same way, only tsss! - user207618If you use the capabilities of ES6, then create a function that determines the sequence of odd numbers is quite realistic. To do this, use iterators , but only directly, without the syntax sugar generators. And to convert the resulting iterator into an array, you can use Array.from .
This is how the code might look like:
const makeSequence = (len) => { const seq = { [Symbol.iterator]() { return { next() { return { value: (1 + 2 * --len), done: (len < 0) }; } }; } }; return Array.from(seq).reverse(); }; console.log(makeSequence(3)); And here is a working example on JSFiddle .
current - also used to calculate values. But in general, yes, the code can be made more beautiful. Let's leave this task to the TS :) - Dmitriy SimushevSource: https://ru.stackoverflow.com/questions/633133/
All Articles