const add=(x,y,z)=>x+y+z;
const args = [1,2,3];
console.log(add.toString());
console.log(add(args));
console.log(add(...args));
(x,y,z)=>x+y+z
1,2,3undefinedundefined
6
const add = (x, y, z) => x + y + z;
const args = [1, 2, 3];
const add1 = add.bind(null, 1);
console.log(add1(2, 3));
6
const add = (x, y, z) => x + y + z;
console.log(`add.length: ${add.length}`);
console.log(`add.toString: ${add.toString()}`);
console.log(`add.call: ${add.call(null,1,2,3)}`);
const args = [1, 2, 3];
console.log(`add(...args): ${add(...args)}`);
const add1 = add.bind(null, 1);
console.log(`add1(2, 3) with bind 1: ${add1(2,3)}`);
add.length: 3
add.toString: (x, y, z) => x + y + z
add.call: 6
add(...args): 6
add1(2, 3) with bind 1: 6
Convert Array:
The following is a challenge extracted from the LinkedIn Learning ES6 tutorial. The requirement is to count the votes in the elections for each candidate.
const electionVotes = [
'Harry', 'Rick', 'Ben', 'Ben', 'Harry', 'Ashley',
'Connor', 'Rick', 'Ashley', 'Rick', 'Albert', 'Ben',
'Michael', 'Rick', 'Albert', 'Karen', 'Harry',
'Karen', 'Donna', 'Ashley', 'Albert', 'Harry',
'Dane', 'Dane', 'Rick', 'Donna', 'Mortimer',
];
const tallyVotes = (votes) => {
// Your code here <-----------
};
console.log(tallyVotes(electionVotes));
/* Expected Output (something like this):
{
Harry: <some number>
Donna: <some number>
Rick: <some number>
...
}
*/
const tallyVotes = (votes) => {
return votes.reduce((acc,name)=>({
...acc,
[name]: acc[name] ? acc[name] + 1 : 1,
// candidate name : count is defined? if it is...+1.
// if is not candidate name = 1
}),{});
};
And the result…
{ Harry: 4,
Rick: 5,
Ben: 3,
Ashley: 3,
Connor: 1,
Albert: 3,
Michael: 1,
Karen: 2,
Donna: 2,
Dane: 2,
Mortimer: 1 }
Also it could be reduced to 1 line
const tallyVotes = (votes) =>
votes.reduce((acc,name)=>({
...acc,
[name]: acc[name] ? acc[name] + 1 : 1,
}),{});