Wednesday, August 7, 2019

js: on the conditional deleting/removal of things

Making up my p5 "good parts" guide I noticed that a version of the same problem that haunted me in the Java days (safely removing an object from a collection) is still sort of around-
if I have, say, a collection (either an array or an object I'm treating as a hashmap) of key/value objects and I want to remove particular ones, what does that look like?

Probably the cleanest way in modern JS is to set the array equal to a filtered clone of itself:
let arraythings = [
 arraythings = arraythings.filter((thing)=> (thing.msg !== 'killme') ); 

and if that collection were an object:

let things = {
  'a':{msg:'ok1'}, 'b':{msg:'killme'},'c':{msg:'ok2'},
things = Object.entries(things).reduce((acc, [key, value]) => {
    if (value.msg !== 'killme') {
        acc[key] = value;
    return acc;
}, {});

A coworker helped me with that, better approach that my idea of making an array of keys to kill and doing a foreach. But the reduce approach looks kind of ugly to me. I'm glad this situation doesn't come up very often, but I should probably work on being more fluent with reduce().

It is interesting that neither approach is super Funtional Programming-ish, and in both cases I am reassigning the collection variable (though it always seems weird to me that a const object is just guaranteeing that you're pointing to the same collection, not that the contents of said collection are in any way frozen... that's what Object.freeze() is for.

No comments:

Post a Comment