Re:What if you couldn’t program with loops?
by deaddodo on Monday July 15, 2019 @02:54AM
(#20438687)
I agree. The correct solution (given javascript as the language of choice) is something along the following lines:
Personally, I think this exercise is completely fruitless except to teach recursion.
[ Parent
| on HN ]
By using rest is possible to write it in an immutable (and nicer) way:
const highlightProducts = ([product, ...productsToProcess], processedProducts = []) => {
if(productsToProcess.length === 0) {
return processedProducts;
}
processedProducts.push({
...product,
highlighted: product.name.indexOf('mountain') !== -1
|| product.stock > 100 && product.price < 5
|| product.category == 'outdoors' && product.price < 35 && product.price > 20
})
return highlightProducts(productsToProcess, processedProducts);
}
or in shorter: const highlightProducts = ([product, ...productsToProcess], processedProducts = []) =>
productsToProcess.length === 0
? processedProducts
: highlightProducts(productsToProcess, [
...processedProducts,
{
...product,
highlighted: product.name.indexOf('mountain') !== -1
|| product.stock > 100 && product.price < 5
|| product.category == 'outdoors' && product.price < 35 && product.price > 20
}
])
Re:What if you couldn’t program with loops?
by deaddodo on Tuesday July 16, 2019 @12:51AM
(#20447556)
I agree this is a better solution and immutability is preferable.
Re:What if you couldn’t program with loops?
by dan-robertson on Monday July 15, 2019 @05:57AM
(#20439347)
I was expecting the answer to look something like:
products.forEach((p) =>
p.highlighted = (
/mountain/.test(p.name)
|| (p.stock > 100 && p.price < 5)
|| (p.category == 'outdoors' && 20 < p.price && p.price < 35)))
And if one wants the (implicitly hidden) behaviour that highlighted products stay highlighted forever, just add the condition p.highlighted to the disjunction above.
Re:What if you couldn’t program with loops?
by deaddodo on Monday July 15, 2019 @04:44PM
(#20445056)
forEach is a loop, so this doesn't answer the basic question OP presented.
Re:What if you couldn’t program with loops?
by dan-robertson on Monday July 15, 2019 @07:23PM
(#20446207)
The standard doesn’t specify whether or not forEach is a “loop” or not. One could implement it using tail recursion. FWIW I would claim that such recursion should also be called a loop, because the control flow goes in a loop.
Re:What if you couldn’t program with loops?
by deaddodo on Tuesday July 16, 2019 @12:48AM
(#20447545)
You're splitting hairs. I think we can both agree that no implementation does it as such. And if you're going to go to that low of a level, there's no such thing as a loop beyond emergent behavior (they're all conditional branches/jumps).
Re:What if you couldn’t program with loops?
by dhbradshaw on Monday July 15, 2019 @12:04PM
(#20442087)
Want a job?
;-D