I was looking at this example of reduce() at https://putaindecode.io/articles/array-reduce-par-l-exemple/
var stats = [
{ site: "google.fr", browser: "Chrome", value: "50%" },
{ site: "google.fr", browser: "FireFox", value: "30%" },
{ site: "google.fr", browser: "Internet Explorer", value: "20%" },
{ site: "mozilla.fr", browser: "FireFox", value: "60%" },
{ site: "mozilla.fr", browser: "Internet Explorer", value: "20%" },
{ site: "microsoft.fr", browser: "Chrome", value: "10%" },
{ site: "microsoft.fr", browser: "FireFox", value: "20%" },
];
function compareSite(site, item) {
return site === item.site;
}
function containSite(site, items) {
return items.some(compareSite.bind(null, site));
}
function groupBySite(memo, item) {
var site = memo.filter(containSite.bind(null, item.site));
if (site.length > 0) {
site[0].push(item);
} else {
memo.push([item]);
}
return memo;
}
// We use an empty array as accumulator
var results = stats.reduce(groupBySite, []);
console.log(results);
and the result is:
[
[
{ site: 'google.fr', browser: 'Chrome', value: '50%' },
{ site: 'google.fr', browser: 'FireFox', value: '30%' },
{ site: 'google.fr', browser: 'Internet Explorer', value: '20%' }
],
{ site: 'mozilla.fr', browser: 'FireFox', value: '60%' },
{ site: 'mozilla.fr', browser: 'Internet Explorer', value: '20%' }
],
[
{ site: 'microsoft.fr', browser: 'Chrome', value: '10%' },
{ site: 'microsoft.fr', browser: 'FireFox', value: '20%' }
]
]
I don't understand some things:
Why in containSite function ".bind(null, site)" is necessary?
Why in groupBySite function ".bind(null, item.site)" is used and not the previous ".bind(null, site)"?
The author used the bind syntax to "prefill" the first argument of the passed function, much like below.
function fn(a, b, c, d) {
console.log({ a, b, c, d });
}
fn.bind(null, 1, 2)('c', 'd')
fn(1, 2, 'c', 'd');
Most people will not like you for using the first syntax, because most people will need to look up the exact usage of the bind...
Usually bind is used to change the value of this inside of the function passed to bind.
As I know, containSite and containSite2 are equivalent
function compareSite(site, item) {
return site === item.site;
}
function containSite(site, items) {
return items.some(compareSite.bind(null, site));
}
function containSite2(site, items) {
return items.some((items) => compareSite(site, items));
}
Usually bind is used to change this pointer inside function:
function fn() { console.log(this) };
let binded_fn = fn.bind("Hello, World!"); // bind this with string "Hello, World!"
binded_fn(); // String {'Hello, World!'}