javascript - Underscore JS _.partial reduce maintaining memo reference and casting integers to string? -
given next (simplified) code, attempting dynamically calculate bootstrap grid:
(function() { var reducecalc = _.partial(_.reduce, _, function(memo, entry) { console.log(entry); console.log((_.last(memo) + parseint(entry))); if (!entry || (parseint(_.last(memo) + parseint(entry)) <= 12)) { _.last(memo).push(entry); } else { memo.push([entry]); } homecoming memo; }, [ [] ]); var onelist = [6, 6]; var twolist = [7, 5, 4, 6]; var rowlistone = reducecalc(onelist); var rowlisttwo = reducecalc(twolist); console.log(rowlistone); console.log(rowlisttwo); })();
two questions,
the parseint
necessary, because without sec console log: console.log((_.last(memo) + entry));
casts both integers strings , returns "66", "75". why that?
the second, , much more major question is: why appear maintain reference memo, rather resetting [[]] per run? final console logs are:
[array[0], array[2], array[3], array[1]] [array[0], array[2], array[3], array[1]]
why maintain reference? how can avoid doing so? demo plunkr here:
http://plnkr.co/edit/dtbgrisg4milguoaureu?p=preview
let @ parseint
stuff first. underlying problem sort of things you're storing in memo
:
memo.push([entry])
so entries of memo
single element arrays , _.last(memo)
array. if seek array + something_else
you'll end coercing strings , doing string concatenation because, more or less, ends getting stringified when javascript doesn't know else do. want within arrays within memo
:
console.log(_.last(memo)[0] + entry)
keep in mind console.log
variadic say:
console.log(_.last(memo), entry)
that leave confusing live references in console maybe better:
console.log(_.clone(_.last(memo)), entry)
your sec problem reference problem. you're saying things:
var fn = function(memo,entry) { ... }; var aoa = [ [ ] ]; var reducecalc = _.partial(_.reduce, _, fn, aoa);
that aoa
array stashed within reducecalc
, exact array used every invocation of reducecalc
. there's nil anywhere in code create new array each invocation.
if want new array you'd need this:
var reducecalc = _.partial(_.reduce, _, function(memo, entry) { memo = memo || [ [ ] ]; // create new array specific invocation //... homecoming memo; }, null);
the odd looking null
needed trick _.reduce
supplying null
value memo
first time calls callback, _.reduce
utilize argument's first entry initial memo
if don't specify explicit one.
javascript functional-programming underscore.js pass-by-reference
No comments:
Post a Comment