Skip to content

Instantly share code, notes, and snippets.

@michaelNgiri
Last active March 5, 2019 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelNgiri/1079b5c5238bf256c16ead895b9d28de to your computer and use it in GitHub Desktop.
Save michaelNgiri/1079b5c5238bf256c16ead895b9d28de to your computer and use it in GitHub Desktop.
hackerbay test, stock analyser, array flattener
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.action-btn-group{
margin: 4px; margin-left: 40vw; padding: 10px; cursor: grab; font-size: 1.4em;
}
</style>
</head>
<body>
<div>
<br>
<span style="color: red;">open the browser <em>console </em> view the output</span>
<br>
<button class="action-btn-group" onclick="flatten([1,2,[3,4,[5,6],7,[8,9]]])">Flatten array</button>
<br>
<br>
<button class="action-btn-group" onclick="go()">get Stock values</button>
<br>
</div>
<script type="text/javascript">
//list of test cases
const array1 = [200, 1,5,6,7,34,10];
const array2 = [1,5,6,7,34,10,300];
const array3 = [10,1,5,6,7,34,10,20];
const array4 = [2,200,1,0,10];
const array5 = [7,10];
//execute functions with the test cases
function go(testValues) {
console.log('key: [buy day, sell day]');
console.log('');
getFinalValue(array1)
getFinalValue(array2)
getFinalValue(array3)
getFinalValue(array4)
getFinalValue(array5)
}
//organize the functions
function getFinalValue(array){
finalArray = [];
getMinStockValue(array);
getMaxStockValue(array);
if (finalArray[1] - finalArray[0] == 0) {
console.log([0,0])
}else{
console.log('stock value pairs: '+'['+finalArray+']');
}
}
//initialize an empty array that will hold the final value
let finalArray = [];
//find the day of highest stock value
function getMaxStockValue(arr) {
if (arr.length === 0) {
return -1;
}
let max = arr[0];
let maxIndex = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
finalArray.push(maxIndex)
return maxIndex;
}
//find the day of lowest stock value
function getMinStockValue(arr) {
if (arr.length === 0) {
}
const smallestValue = arr.indexOf(Math.min.apply(Math, arr))
finalArray.push(arr.indexOf(Math.min.apply(Math, arr)))
return smallestValue;
}
///////////////////////////////////////////////////////////////////////
// ///flatten array
function flatten(arr) {
var flattennedArray = [];
function recursiveFlatten(arr) {
for(var i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
recursiveFlatten(arr[i]);
} else {
flattennedArray.push(arr[i]);
}
}
}
recursiveFlatten(arr);
console.log(flattennedArray)
console.log('')
return flattennedArray;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment