Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active November 9, 2022 11:21
Show Gist options
  • Save sebinsua/522a0725a0c547b9083eebc36662f5b1 to your computer and use it in GitHub Desktop.
Save sebinsua/522a0725a0c547b9083eebc36662f5b1 to your computer and use it in GitHub Desktop.
// Replace items in `as` with a matching `id` with the
// respective item in `bs`, otherwise append new items.
const abs = Object.fromEntries([
...as.map(a => [a.id, a]),
...bs.map(b => [b.id, b])
]);
// The 'trick' is that if you have two entries with the same id
// (in this case, implying that the value was updated within `bs`)
// then with this method the value of the right-most entry will be used.
@sebinsua
Copy link
Author

sebinsua commented Nov 8, 2022

As for grouping:

function append(previousItems = [], element, index, array) {
  return previousItems.concat([element]);
}

function groupToMap(items, callbackFn, reduceFn = append) {
  if (!Array.isArray(items)) {
    throw new Error(`groupToMap must receive an array as its first argument.`);
  }
  if (typeof callbackFn !== "function") {
    throw new Error(
      `groupToMap must receive a function as its second argument.`
    );
  }
  if (typeof reduceFn !== "function") {
    throw new Error(
      `groupToMap must receive a function as its third argument.`
    );
  }
  return items.reduce((map, element, index, array) => {
    const key = callbackFn(element, index, array);
    return map.set(
      key,
      map.has(key) ? reduceFn(map.get(key), element, index, array) : reduceFn(undefined, element, index, array)
    );
  }, new Map());
}

function group(items, callbackFn, appendFn = append) {
  return Object.fromEntries(groupToMap(items, callbackFn, appendFn).entries());
}

Create two partitions for odd and even values containing a count of the number of items belonging to these partitions:

groupToMap(
  [1, 2, 3, 4, 5],
  (v) => (v % 2 === 0 ? "even" : "odd"),
  (previous = 0) => previous + 1
);
// Map {"odd" => 3, "even" => 2}

Create two partitions for odd and even values containing the sum of the values within these partitions:

groupToMap(
  [1, 2, 3, 4, 5],
  (v) => (v % 2 === 0 ? "even" : "odd"),
  (previous = 0, v) => previous + v
);
// Map(2) {"odd" => 9, "even" => 6}

@sebinsua
Copy link
Author

sebinsua commented Nov 9, 2022

If I get time I will implement an immutable version of Counter.

function total(map) {
  return map.values().reduce((acc, count) => acc + count, 0);
}

function mostCommon(map, n) {
  // ...
  // Not trivial to do well, so I'll come back to this... :)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment