Skip to content

Commit

Permalink
Adding sorting functionality
Browse files Browse the repository at this point in the history
Adding extra check on key parameter in search func
Updating read me for sorting
version 1.0.1

Signed-off-by: Amgad Fahmi <amgadnady@gmail.com>
  • Loading branch information
amgadfahmi committed May 27, 2016
1 parent 2e4d9eb commit 733694c
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 8 deletions.
14 changes: 11 additions & 3 deletions README.md
Expand Up @@ -25,7 +25,7 @@ for (var i = 0; i < 10000; i++) {
arrNum.push(i + 1);
}
var result = new BS(arrNum).search(9999);
console.log(result) //9999
console.log(result) //output is 9999
```

## Comparison with Linear search
Expand Down Expand Up @@ -53,8 +53,16 @@ The search function has 2 overloads:
```javascript
new BS(arrObj).search('20380a36-8777-43f7-a79e-65bdb53f4621', 'guid');
```
## Roadmap
Add sort feature for any kind of array...
## Sorting
Now you can sort the array in chaining mechanism.
```javascript
new BS([3,1,66,33,890,24]).sort().search(66); //output is 66
//or
var arr = [{id:33, name:'Jasmin'},{id:12, name:'David'},{id:7, name:'Amgad'},{id:56, name:'Katya'}];
new BS(arr).sort('id').search(7,'id'); //output is {id:7, name:'Amgad'}
new BS(arr).sort('name').search('Katya','name'); //output is {id:56, name:'Katya'}

```
## License

The MIT License (MIT)
Expand Down
39 changes: 35 additions & 4 deletions lib/js-binarysearch.js
@@ -1,15 +1,18 @@
'use strict';

var BS = function (array) {
var BS = function(array) {
if (array) {
this.internalArray = array;
} else {
throw new error('Object is not defined');
}
return this;
};



BS.prototype.search = function(target, key) {
if (key) {
if (key && typeof key === 'string') {
return this.searchObj(target, key);
} else if (typeof target === 'number') {
return this.searchNum(target);
Expand All @@ -19,8 +22,8 @@ BS.prototype.search = function(target, key) {
};

BS.prototype.searchNum = function(target) {
var min = this.internalArray[0],
max = this.internalArray[this.internalArray.length - 1],
var min = 0,
max = this.internalArray.length - 1,
mid;
while (min <= max) {
mid = Math.round(min + (max - min) / 2);
Expand Down Expand Up @@ -67,3 +70,31 @@ BS.prototype.searchObj = function(target, key) {
}
}
};


BS.prototype.sort = function(key) {
if (this.internalArray.length <= 1) {
return;
}
if (key && typeof key === 'string') {
this.sortObj(key);
return this;
} else {
this.internalArray.sort();
return this;
}
};

BS.prototype.sortObj = function(key) {
var isString = typeof this.internalArray[0][key] === 'string';
if (isString) {
this.internalArray.sort(function(a, b) {
return a[key].localeCompare(b[key]);
});
} else {
this.internalArray.sort(function(a, b) {
return a[key] - b[key];
});
}

};
1 change: 0 additions & 1 deletion test/test.html
Expand Up @@ -27,7 +27,6 @@
loadChart(iterations);
});


</script>
</head>
<body>
Expand Down

0 comments on commit 733694c

Please sign in to comment.