javascript - Creating a simplified underscore _.invoke -
i trying create underscore's _.invoke function. can't figure out why keep getting typeerror, cannot read property 'sort' of undefined. assume refers array being passed function, can log each array in collection, don't know why undefined in being thrown up.
function each(collection, iteratee, context) { let let bounditeratee = iteratee.bind(context) if (array.isarray(collection)) { (i = 0; < collection.length; i++) { bounditeratee(collection[i], i, context) } } else { (i in collection) { if (collection.hasownproperty(i)) { bounditeratee(collection[i], i, collection); } } } return collection } function map(collection, iteratee, context) { let result = [] let formula = function(element, index) { result.push(iteratee(element, index, context)) } each(collection, formula, context) return result } function invoke(collection, methodname) { let args = array.prototype.slice.call(arguments, 2) let formula = function(array, index) { //console.log(array) --> returns arrays in collection... return methodname.apply(array, args) } return map(collection, formula) } function sortit(array) { return array.sort() } console.log(invoke([ [3, 1, 2], [7, 6, 9] ], sortit))
depending on you're trying achieve, can either replace sortit function with:
function sortit() { return this.sort(); } // since apply arrays context function or replace
return methodname.apply(array, args); with
return methodname(array); neither ideal, though.
also, please apply() method.
Comments
Post a Comment