const getMostRecentNote = () => {
let maxTimestamp = 0;
let maxId = -1;
notes.forEach((n) => {
if (maxTimestamp < n.lastEdit) {
maxTimestamp = n.lastEdit;
maxId = n.id;
}
});
// https://stackoverflow.com/a/43576363/4907950
const rtn = notes.reduce((acc, note) => {
if (acc.maxTimestamp === undefined) {
acc = { maxTimestamp: -1, maxId: -1 };
}
if (note.lastEdit > acc.maxTimestamp) {
acc = { maxTimestamp: note.lastEdit, maxId: note.id };
}
return acc;
}, {}).maxId;
return [maxId, rtn];
};
```Update: realized I can just logical or the reduce one:
const rtn = notes.reduce((acc, note) => {
if (
acc.maxTimestamp === undefined ||
note.lastEdit > acc.maxTimestamp
) {
acc = { maxTimestamp: note.lastEdit, maxId: note.id };
}
return acc;
}, {}).maxId;
I still like the simple version better but let me know what you think or if you can think of something simpler : )
Update 2: Even simpler:
const rtn = notes.reduce(
(acc, note) =>
acc.maxTimestamp === undefined || note.lastEdit > acc.maxTimestamp
? { maxTimestamp: note.lastEdit, maxId: note.id }
: acc,
{}
).maxId;
or:
const rtn = notes.reduce(
(acc, note) =>
note.lastEdit > acc.maxTimestamp
? { maxTimestamp: note.lastEdit, maxId: note.id }
: acc,
{ maxTimestamp: -1 }
).maxId;