Skip to content

Instantly share code, notes, and snippets.

@chrisbautista
Last active January 29, 2024 00:07
Show Gist options
  • Select an option

  • Save chrisbautista/94b577a76aa51daaeeb209954dbe7374 to your computer and use it in GitHub Desktop.

Select an option

Save chrisbautista/94b577a76aa51daaeeb209954dbe7374 to your computer and use it in GitHub Desktop.
Sum without highest and lowest number

Task

Sum all the numbers of a given array ( cq. list ), except the highest and the lowest element ( by value, not by index! ).

The highest or lowest element respectively is a single element at each edge, even if there are more than one with the same value.

Mind the input validation.

Example

{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6

Input validation

If an empty value ( null, None, Nothing etc. ) is given instead of an array, or the given array is an empty list or a list with only 1 element, return 0.

import solution = require('./SumWithoutLowestAndHighestNumber.ts');
import {assert} from "chai";
describe("KataTest", function(){
it("BasicTests", function(){
assert.deepEqual(solution.sumArray([ 6, 2, 1, 8, 10 ]), 16);
assert.deepEqual(solution.sumArray([ 6, 0, 1, 10, 10 ]), 17);
assert.deepEqual(solution.sumArray([ 1, 1, 11, 2, 3 ]), 6);
assert.deepEqual(solution.sumArray([ ]), 0);
assert.deepEqual(solution.sumArray([ 1 ]), 0);
assert.deepEqual(solution.sumArray(null), 0);
assert.deepEqual(solution.sumArray(), 0);
});
});
export function sumArray(array ?: Array<number> | null) : number {
if (array?.length && array.every(a => !isNaN(a + 0))) {
// sort
array.sort((a, b) => a - b);
// add all numbers except first and last
let total = 0;
for (let i = 0; i < array.length - 1; i++) {
if (i === 0 || i === array.length - 1) {
continue;
}
total += array[i];
}
return total;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment