Write a function fn
that returns the length of an Array as Number.
Constraints:
- no use of
length
property -
size
and length/size indicating properties of other data structures are also not allowed
Tips:
- try to avoid the comments section, as the solutions are often posted there
- it's way easier than you might think (which is why it's tagged
#beginners
) - read about Array fundamentals
- don't expect the solution to be something that you should ever use in production code
Tests:
console.assert(fn([]) === 0)
console.assert(fn([1]) === 1)
console.assert(fn(['1']) === 1)
console.assert(fn(['1', 2, {}]) === 3)
Bonus:
This is all achievable by using 20 characters (inkl. function declaration) overall.
Top comments (5)
Push returns the length; otherwise one could use recursion:
const fn = arr => arr.reduce(acc => acc + 1, 0);
16 chars using push...
In my opinion, this is not a solution because push returns the new array length.
If I solve it recursively, the smallest variant is 26 chars long.
Therefore I would be interested in the 20 chars solution.
The puzzles are not looking for solutions, that are valid to be used in the real world (I should have mentioned that in the article). It's more intended to make people think out f the box and have a fun way to do some research about fundamental functionalities. From such a viewpoint, a push solution would be sufficient as it would comply with
fn = Array => Number
.Thank you for the info!