mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Added Linear Search Fix
This commit is contained in:
parent
ceed279de8
commit
45762593b5
@ -4,17 +4,17 @@ describe('linearSearch', () => {
|
|||||||
it('should search all numbers in array', () => {
|
it('should search all numbers in array', () => {
|
||||||
const array = [1, 2, 4, 6, 2];
|
const array = [1, 2, 4, 6, 2];
|
||||||
|
|
||||||
expect(linearSearch(array, 10)).toEqual([]);
|
expect(linearSearch(array, 10)).toEqual(-1);
|
||||||
expect(linearSearch(array, 1)).toEqual([0]);
|
expect(linearSearch(array, 1)).toEqual(0);
|
||||||
expect(linearSearch(array, 2)).toEqual([1, 4]);
|
expect(linearSearch(array, 2)).toEqual(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should search all strings in array', () => {
|
it('should search all strings in array', () => {
|
||||||
const array = ['a', 'b', 'a'];
|
const array = ['a', 'b', 'a'];
|
||||||
|
|
||||||
expect(linearSearch(array, 'c')).toEqual([]);
|
expect(linearSearch(array, 'c')).toEqual(-1);
|
||||||
expect(linearSearch(array, 'b')).toEqual([1]);
|
expect(linearSearch(array, 'b')).toEqual(1);
|
||||||
expect(linearSearch(array, 'a')).toEqual([0, 2]);
|
expect(linearSearch(array, 'a')).toEqual(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should search through objects as well', () => {
|
it('should search through objects as well', () => {
|
||||||
@ -33,8 +33,8 @@ describe('linearSearch', () => {
|
|||||||
{ key: 6 },
|
{ key: 6 },
|
||||||
];
|
];
|
||||||
|
|
||||||
expect(linearSearch(array, { key: 10 }, comparatorCallback)).toEqual([]);
|
expect(linearSearch(array, { key: 10 }, comparatorCallback)).toEqual(-1);
|
||||||
expect(linearSearch(array, { key: 5 }, comparatorCallback)).toEqual([0]);
|
expect(linearSearch(array, { key: 5 }, comparatorCallback)).toEqual(0);
|
||||||
expect(linearSearch(array, { key: 6 }, comparatorCallback)).toEqual([1, 3]);
|
expect(linearSearch(array, { key: 6 }, comparatorCallback)).toEqual(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
@ -10,13 +10,12 @@ import Comparator from '../../../utils/comparator/Comparator';
|
|||||||
*/
|
*/
|
||||||
export default function linearSearch(array, seekElement, comparatorCallback) {
|
export default function linearSearch(array, seekElement, comparatorCallback) {
|
||||||
const comparator = new Comparator(comparatorCallback);
|
const comparator = new Comparator(comparatorCallback);
|
||||||
const foundIndices = [];
|
|
||||||
|
|
||||||
array.forEach((element, index) => {
|
for (let i = 0; i < array.length; i += 1) {
|
||||||
if (comparator.equal(element, seekElement)) {
|
if (comparator.equal(array[i], seekElement)) {
|
||||||
foundIndices.push(index);
|
return i;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
return foundIndices;
|
return -1;
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user