I am learning functional programming in JavaScript. This is some code from a video tutorial by funfunfunction. I am particularly concerned about the way the existence of the customer key is checked in the customers object.
Is it weird to do it this way? Is there any other way? Also, if you switch the order of the OR statement operands, the object is overwritten. Does order matter in an OR statement?
The function:
var fs = require('fs')
var output = fs.readFileSync('data2.txt', 'utf8')
.trim()
.split('\r\n')
.map(function(line) {
return line.split('\t')
})
.reduce(function(customers, line) {
customers[line[0]] = customers[line[0]] || []
customers[line[0]].push({
item: line[1],
quantity: line[2],
price: line[3],
})
return customers
}, {})
console.log('output', JSON.stringify(output, null, 2));
The data:
Marry Poppins red bicycle 80 2 Marry Poppins glass vase 20 8 Abe Lincoln gold ring 1 100 Marry Poppins umbrella 5 50 Steve Rogers video camera 1 100 Abe Lincoln president chair 1 1000 Marry Poppins blue dress 2 200