Skip to content

Instantly share code, notes, and snippets.

@faizahmedfarooqui
Last active March 4, 2021 06:09
Show Gist options
  • Select an option

  • Save faizahmedfarooqui/79682c7e0ac22a33fa45e61e29cd9187 to your computer and use it in GitHub Desktop.

Select an option

Save faizahmedfarooqui/79682c7e0ac22a33fa45e61e29cd9187 to your computer and use it in GitHub Desktop.
Remove transactions that has duplicate source, target, amount & category + the time difference between the transaction is less than 1 minute.
// Converts the time string into Date Object
const timestamp = _time => Date.parse(_time) / 1000;
/**
* 1. group-by given keys
* 2. sort the groups in ascending order for Time key
* 3. filters duplicate entries with time difference < 60 seconds
*
* @param _array Array [required]
* @param _function Function [required]
* @param _seconds Number [required]
* @return Array
*/
const groupBy = (_array, _function, _seconds) => {
return _array
.map(_data => ({
key: JSON.stringify(_function(_data)),
timestamp: timestamp(_data.time),
data: _data
}))
.sort((_a, _b) => (_a.timestamp - _b.timestamp))
.reduce(([_accumulator, _previous], _current) => {
if (
!_previous ||
_current.key != _previous.key ||
_current.timestamp - _previous.timestamp > 60
) _accumulator.push([]);
_accumulator[_accumulator.length - 1].push(_current.data);
return [_accumulator, _current];
}, [[]])[0];
}
/**
* Finds all transactions that have the same sourceAccount,
* targetAccount, category, amount & the time difference
* is less than 1 minute.
*/
function findDuplicateTransactions (transactions = []) {
return groupBy(
transactions,
(_txn) => [
_txn.sourceAccount,
_txn.targetAccount,
_txn.amount,
_txn.category
],
60
).filter(_group => _group.length > 1);
}
findDuplicateTransactions(_transactions);
@faizahmedfarooqui
Copy link
Author

What is the usage of [0] at line 32 ?

As the name suggests, it's the accumulator that holds all the transaction objects. You can return just the accumulator array from the return array. This way you can avoid using [0] from line 32.

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