/* * title "Array.prototype.arrayLength" * author "Dylan Lom" * date "2022-08-05" * link stylesheet "/main.css" */ # $(echo $title) An exercise in stupidity > How do you get the length of an array in JavaScript?
Array.prototype.arrayLength = function () { return this.length }
> I don't trust
Array.prototype.arrayLength = function() {
let len = 0
for (let x in this) {
if (len === 0) len++
len++
}
return len
}
*Aside: I think I'd had too much to drink by this point -- the above implementation*
*is just wrong. Also amusingly iterating `this` actually includes `arrayLength`, which*
*I can't quite explain currently (I guess I'm using prototype wrong?)*
> Ok, but that could you make it look like "modern" js at least?
Array.prototype.arrayLength = function() {
let len = 0
this.forEach((x, i) => len = i + 1)
return len
}
> Surely you don't need three lines?
Array.prototype.arrayLength = function() {
return this.reduce(acc => acc+1, 0)
}
> Sorry but that implementation does not account for setting
> arbitrary indecies:
>
>
> const xs = [1,2,3]
> xs[99] = 100
> xs.length == 100
> xs.arrayLength() == 4
>
**N.B.**: The `for (const x in this)` solution fails at this as well
Array.prototype.arrayLength = function() {
return Math.max(...Object.keys(this).map(x => Number.parseInt(x)).filter(k => !Number.isNaN(k))) + 1
}
> *Clears throught* `[].arrayLength() === -Infinity`
Array.prototype.arrayLength = function() {
return (Object.keys(this).map(x => Number.parseInt(x)).filter(k => !Number.isNaN(k)).sort((a, b) => b - a)[0]) + 1 || 0
}
> I hate you
Array.prototype.arrayLength = function() {
return this.findLastIndex(this.at(-1))
}
> *Cries in non-bleeding-edge-impl*
**N.B.**: I haven't even tested this implementation, since I don't have
any javascripts that support findLastIndex currently.
## Footnote
I actually learnt something about how `.forEach` was implemented by thinking up
and testing these dumb implementations, how novel!
Array.prototype.myForEach = function(f) {
const kvs = Object.entries(this).filter(([k]) => !Number.isNaN(Number.parseInt(k)))
for (let i = 0; i < kvs.length; i++) {
f(kvs[i][1], Number.parseInt(kvs[i][0]))
}
}
It's quite interesting how far we go in pretending that the numeric indecies we
pass in square-braces are actually numbers -- ie. we pass back the numeric
index in the forEach. Or maybe I just don't quite understand it
const xs = [1,2,3]
xs[1] === xs['1']