Skip to content

Instantly share code, notes, and snippets.

@wulymammoth
Created June 20, 2022 19:24
Show Gist options
  • Save wulymammoth/b3ee91a2a72e0ab11853a0303a262db2 to your computer and use it in GitHub Desktop.
Save wulymammoth/b3ee91a2a72e0ab11853a0303a262db2 to your computer and use it in GitHub Desktop.
How to write your own test cases and test
/*
You are given an array `numbers` and an integer `pivot`
Your task is to return a new array in with the i-th element equals:
- 0 if numbers[i] is zero
- 1 if numbers[i] and the pivot have the same sign
- -1 if the numbers[i] and the pivot have differing signs
*/
function assessNums(nums, pivot) {
const output = []
nums.forEach(num => {
if (num === 0) {
output.push(0)
} else if ((num < 0 && pivot < 0) || (num >= 0 && pivot >= 0)) {
output.push(1)
} else { // differing signs
output.push(-1)
}
})
return output;
}
const testCases = [
{
args: [ [6, -5, 0], 2 ],
expected: [1, -1, 1]
},
{
args: [[5, -4, 0, -3, 2], -5],
expected: [-1, 1, 0, 1, 1]
},
// third test case and expected result, etc
]
testCases.forEach((testCase, idx) => {
// destructuring assignment
[numbers, pivot] = testCase.args;
const got = assessNums(numbers, pivot);
// NOTE: must use `JSON.stringify` to do array equality checks
if (JSON.stringify(got) != JSON.stringify(testCase.expected)) {
const errorMsg = [
`test case ${idx + 1} FAILED`,
'-----',
`GOT:\n\t${got}`,
'\n',
`EXPECTED:\n\t${testCase.expected}`,
'\n\n'
]
console.error(errorMsg.join('\n'));
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment