Tuesday, 6 November 2018

Linear search in typescript ( Data structure)

A simple linear search using typescript.....

//create a node object (interface) which hold's index and any type of data
interface node {
index: number;
value: any;
}
//base class which hold's array of nodes inside data array
class Search {
public data: Array<any> = new Array();
constructor() { };
}
//extend Search class
class LinearSearch extends Search {

constructor(_data: Array<any>) {
super();
this.data = _data;
}
public search(_value) {
for (var i = 0; i < this.data.length; i++) {
if (this.data[i] === _value) {
return { index: i, value: this.data[i] };
}
}
}
}

var linearSearch = new LinearSearch([4, 5, 11, 23, 12]);
//get search index
console.log(linearSearch.search(23).index);

No comments:

Post a Comment

understanding promise and async function using example

working link-> https://stackblitz.com/edit/js-it5ura?file=index.js //passing value to a promise using arrow function let numberS...