Skip to content

Instantly share code, notes, and snippets.

@danielmeneses
Last active November 20, 2018 01:35
Show Gist options
  • Save danielmeneses/ff1c3867e059efea312c8375de4273ec to your computer and use it in GitHub Desktop.
Save danielmeneses/ff1c3867e059efea312c8375de4273ec to your computer and use it in GitHub Desktop.
sort array - mean calc
/**
* Merge sort - high performance sorting
*/
const mergeSort = (input, field) => {
const splitted = [];
for (let i = 0; i < input.length; i++) splitted.push([input[i]]);
const merged = (function merge(arr) {
const tempResult = [];
for (let i = 0; i < arr.length; i += 2) {
const result = [];
const current = i;
const next = i + 1;
let left = 0;
let right = 0;
// for odd arrays, if doesn't has next then it's odd therefore need to push the current array
if (!arr[next]) tempResult.push(arr[current]);
else {
while (left < arr[current].length || right < arr[next].length) {
// case there's only one element remaining (odd number of elements)
if (left === arr[current].length && right < arr[next].length) {
result.push(arr[next][right]);
right++;
continue;
} else if (left < arr[current].length && right === arr[next].length) {
result.push(arr[current][left]);
left++;
continue;
}
const val1 = arr[current][left][field];
const val2 = arr[next][right][field];
if (val1 < val2) {
result.push(arr[current][left]);
left++;
} else {
result.push(arr[next][right]);
right++;
}
}
tempResult.push(result);
}
}
if (tempResult.length > 1) return merge(tempResult);
else return tempResult;
})(splitted);
return merged[0];
}
/**
* Exception - not a number
*/
function NotANumberException(msg) {
this.message = msg;
this.name = 'NotANumberException';
}
/**
* Calculate mean
*/
const meanCalc = (objList, field) => {
if(typeof objList !== 'object' || !objList.length) return null;
let total = 0;
for (let i = 0; i < objList.length; i++) {
const item = objList[i];
if(item.hasOwnProperty(field) && typeof item[field] === 'number')
total += objList[i][field];
else
throw new NotANumberException(`The provided object ${field} for item`, item, 'is not a valid number');
}
return total / objList.length;
}
// example:
const a = [
{ name: 'Mr. Burns', age: 145 },
{ name: 'Moe', age: 37 },
{ name: 'Apu', age: 39 },
{ name: 'Carl', age: 34 },
{ name: 'Homer Simpson', age: 38 },
{ name: 'Marge Simpson', age: 36 },
{ name: 'Lisa Simpson', age: 12 },
{ name: 'Bart Simpson', age: 34 },
{ name: 'Maggie Simpson', age: 2 },
{ name: 'Krusty', age: 35 }
];
console.time('mergeSort');
// sort by age
const sortedArray = mergeSort(a, 'age');
console.timeEnd('mergeSort');
console.log(sortedArray);
// calculate mean
console.log('Age mean is: ', meanCalc(sortedArray, 'age'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment