forked from ayan-b/Linear-Search
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(ayan-b#1): JS linear search - input
- Loading branch information
Showing
1 changed file
with
18 additions
and
1 deletion.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,20 @@ | ||
const readline = require('readline') | ||
|
||
const rl = readline.createInterface({ | ||
input: process.stdin, | ||
output: process.stdout | ||
}) | ||
|
||
rl.question('Type the array elements, ie: 12345 ', (elements) => { | ||
rl.question('Type the element to search ', (n) => { | ||
const l = elements.length | ||
const found = linearSearch(elements.split(''), n) | ||
console.log(found > -1 ? `Element found at ${(l-found)}` : `No element found`) | ||
rl.close(); | ||
}) | ||
}) | ||
|
||
const linearSearch = (arr, n) => { | ||
return arr.length ? arr[0] === n || linearSearch(arr.slice(1), n) : false | ||
return arr.length ? (arr[0] === n ? arr.length : linearSearch(arr.slice(1), n)) : -1 | ||
} | ||
|