I’ve been taking JS courses on Execute Program, which as been excellent.
I’m currently learning about Array’s in-depth and wondering if this is a readable way to achieve the null object pattern. No conditionals!
const sales_tax = [
{ name: 'WA', tax: 0.10 },
{ name: 'OR', tax: 0.9 },
];
sales_tax[-1] = { state: 'nan', tax: 0 }
// -1 index is not in `keys` so forEach and other enumerators will not access it
sales_tax.forEach( state => console.log(`State: ${state.name}`));
// State: WA
// State: OR
// See, no `nan`!
console.log( sales_tax.map( state => state.name))
// [ 'WA', 'OR' ]
// no `nan` here either
const customers = [
{ name: 'Travis', state: 'WA' },
{ name: 'Tiny Travis', state: 'XX' },
];
const payable_tax = (state) => {
// if I did a look up with `find` it would return `undefined`.
// By retrieving the index for look up, I instead get -1
const index = sales_tax.findIndex( e => e.name === state );
return sales_tax[index].tax; // No nil check, just call tax!
}
customers.forEach( customer => console.log(`${customer.name} will pay ${payable_tax(customer.state) * 5.00} in taxes`));
// Travis will pay 0.5 in taxes
// Tiny Travis will pay 0 in taxes
This JS code is confident. It never has to check state , handle nil or undefined.