Skip to content

Commit

Permalink
Add get first recurring array element func
Browse files Browse the repository at this point in the history
Signed-off-by: Darko Draskovic <[email protected]>
  • Loading branch information
darkodraskovic committed Jun 26, 2021
1 parent 37cbef8 commit 96bcb05
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import { doTwoMemSumTo } from './utils.js'
import { reverseStringLambda } from './utils.js'
import { mergeSorted } from './utils.js'
import { getFirstRecurring } from './utils.js'
import { getFirstRecurringSlow } from './utils.js'
import { HashTable } from './hash-table.js'

// const arr1 = ['a', 'b', 'c', 'd', 'e'];
Expand Down Expand Up @@ -32,4 +34,20 @@ console.log(myHashTable.get('pears'));
console.log(myHashTable.keys());
console.log(myHashTable);

console.log("\ngetFirstRecurringSlow");
console.log((getFirstRecurringSlow([2, 5, 1, 2, 3, 5, 1, 2, 4])));
console.log((getFirstRecurringSlow([2, 5, 5, 2, 3, 5, 1, 2, 4])));
console.log((getFirstRecurringSlow([2, 3, 4, 5])));
console.log((getFirstRecurringSlow([1])));
console.log((getFirstRecurringSlow([])));
console.log((getFirstRecurringSlow([1,1])));
console.log((getFirstRecurringSlow([2,5,4,3,4,5,2,1])));

console.log("\ngetFirstRecurring");
console.log((getFirstRecurring([2, 5, 1, 2, 3, 5, 1, 2, 4])));
console.log((getFirstRecurring([2, 5, 5, 2, 3, 5, 1, 2, 4])));
console.log((getFirstRecurring([2, 3, 4, 5])));
console.log((getFirstRecurring([1])));
console.log((getFirstRecurring([])));
console.log((getFirstRecurring([1,1])));
console.log((getFirstRecurring([2,5,4,3,4,5,2,1])));
22 changes: 22 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,25 @@ export function mergeSorted(a, b) {
}
return c.concat(ai < a.length ? b.slice(bi) : a.slice(ai));
}

export function getFirstRecurringSlow(arr) {
let leastIdx = Infinity;
for (let i = 0; i < arr.length; i++) {
if (i + 1 > leastIdx) break;
for (let j = i+1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
if (j < leastIdx) leastIdx = j;
break;
}
}
}
return arr[leastIdx];
}

export function getFirstRecurring(arr) {
const occuring = {};
for (let i = 0; i < arr.length; i++) {
if (occuring[arr[i]]) return arr[i];
else occuring[arr[i]] = true;
}
}

0 comments on commit 96bcb05

Please sign in to comment.