BFE.dev#146. implement Array.prototype.reduce() | JSer - Front-End Interview questions

preview_player
Показать описание

An easy polyfill problem.

Hi I'm a JavaScript engineer who is not good at algorithms,
and currently practicing leetCode & BFE.dev. If you are interested, maybe we can learn together.
Рекомендации по теме
Комментарии
Автор

hi jser, thank you for these amazing collaboration to bfe.dev. have been following your channel for a while. I just tried to solve this one. I found something strange.

Array.prototype.myReduce = function (func, initial){

if(this.length===0 && initial===undefined){
throw new Error("array must not empty when no initial value passed")
}
let acc=
let start= arguments.length>1?0:1;
for(let i=start; i<this.length; i++){
***////in the following line i forgot to pass the index and arr ////***
acc= func(acc, this[i])
}
return acc;
}


as expected it said multiple params should be passed with a "spec" and a "diff",
i copied all example in the spec & diff.

when I corrected it acc= func(acc, this[i], i, this) it accepted but
when I tried to test it with previously copied test case it did not get the specified expected answer.
here is the example that I tried,


const arr = [6, 5, 4, 3, 2, 1]
const reducer = (a, b, c, d) => {
if (Array.isArray(a)) {
a.push([b, c, d])
return a
} else {
return [b, c, d]
}
}

**//// this the expected answer ///**


[
[6, 0, [6, 5, 4, 3, 2, 1]],
[5, 1, [6, 5, 4, 3, 2, 1]],
[4, 2, [6, 5, 4, 3, 2, 1]],
[3, 3, [6, 5, 4, 3, 2, 1]],
[2, 4, [6, 5, 4, 3, 2, 1]],
[1, 5, [6, 5, 4, 3, 2, 1]]
]


**//// this was my result ////**
[
5,
undefined,
undefined,
[4, undefined, undefined],
[3, undefined, undefined],
[2, undefined, undefined],

[1, undefined, undefined]
]


I even tried with other solutions from the discussions including yours and
it gave same results as mine. If you are interested Please share your opinion in this.

pratyashabanerjee
join shbcf.ru