This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. |
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}
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
Another idea, might be to group by values other than
id
in order to "select" more aggressively (e.g. instead of removing items with the sameid
, we could key by something else like a hash of some of the internal values).