For a code challenge I thought it'd be useful to have a helper function to group positives and negatives into their own sub arrays while maintaining the ordering of the original array. I'm sure there's a better way to do this but wanted to take a crack at it before researching.
This idea came to mind, to track the state of the numbers, either positive or negative, and group them according to state. This is just MVP and I didn't account for 0.
Despite being verbose, does the code make sense> Do you have recommendations for improvement?
//compare two numbers state
function negAndPosCompare(numA: number, numB: number) {
if (numA > 0 && numB > 0) {
// we'll call 1 our positive state
return 1;
}
else if (numA < 0 && numB < 0) {
// we'll call -1 our negative state
return -1
}
else {
// false is if two numbers are not the same state
return false;
}
}
//simply return the state of a single number
function getState (num : number) {
if (num > 0){
return 1;
}
else if (num < 0) {
return -1;
}
}
function subArray_pos_and_neg(arr: number[]) {
// our final return
const output: number[][] = [];
//where we'll hold numbers of the same state, it'll be exclusive, either pos, or neg.
// we can default it to the very first number. It's a temp because we'll keep recycling it whenever state changes.
let temp_sameKind = [arr[0]];
// grab the state right away, are we starting with pos or neg?
let currentState = getState(arr[0]);
for (let i = 0; i < arr.length; i++) {
// check that i is gte -> 1 so we can safely check arr[i-1]
if (i >= 1) {
//if the current number compared to the last number are not the same state, then that means the streak of a given state is over
if (negAndPosCompare(arr[i], arr[i - 1]) === false) {
//grab the new state.
currentState = getState(arr[i]);
//push the numbers of the same state that we've accumulated so far, they belong together and we'll reset our temp holder
//to accomodate our new state of numbers
output.push(temp_sameKind);
temp_sameKind = [];
//push the current number right away, it is the first number of our new state. this operation is similiar to how we defaulted our
// temp_sameKind array right off the bat (before the for loop). if we don't push it now it'll go missing.
temp_sameKind.push(arr[i]);
}
// the current number is of the same state as our current streak, therefore we want to include it in our accumulation.
if (negAndPosCompare(arr[i], arr[i - 1]) === currentState) {
temp_sameKind.push(arr[i]);
}
}
}
// this check outside of the for loop is the final push of our accumulated numbers... if we don't accomodate the last state of numbers,
// they'll be excluded by our previous logic (since the state doesn't change again in the for loop)
if (temp_sameKind){
output.push(temp_sameKind);
}
return output;
}
subArray_pos_and_neg([1,2,-4,2,5,-6,-3,3,-6,8,9]); //?