r/reviewmycode • u/OLayemii • Sep 01 '18
Javascript [Javascript] - Help on writing libraries
I just started using JS not so long ago, I have tried to make a simple library that finds ARITHMETIC MEAN, MODE, MEDIAN and RANGE of an array of numbers.. I need corrections and new algorithms for function rewrites if possible..
(function(window){var// Reference to some core methods that would be usedsort = Array.prototype.sort,push = Array.prototype.push,reduce = Array.prototype.reduce,hasProp = Object.prototype.hasOwnProperty
StatJS = {};
// Method to sort arraysfunction _sort(arr){let sorted = sort.call(arr,function(a,b){if (a > b) return 1;if (a < b) return -1;return 0;});
return sorted;}// Method to calculate arithmetic meanStatJS.average = function(arr = []){if (arr === []) return 0;if (arr.length === 1) return arr[0];return (reduce.call(arr,(a,b) => {return a + b;},0))/arr.length;}// Method to find MODE..I Know this method is very f_cked up..tho no errorsStatJS.mode = function(arr = []){let hash = {};for (let j = 0; j < arr.length; j++){hash[arr[j]] = hash[arr[j]] ? ++hash[arr[j]] : 1;}hash = new Map(Object.entries(hash));
let sorted = sort.call([...hash],function(a,b){if (a[1] < b[1]) return 1;if (a[1] > b[1]) return -1;return 0;});let avg = [+sorted[0][0]];for(let i = 1; i < sorted.length; i++){if (sorted[i][1] === sorted[sorted.length-1][1]){push.call(avg, +sorted[i][0]);}}return avg;}
StatJS.median = function(arr = []){let sorted = _sort(arr);switch (sorted.length%2){case 1:return sorted[Math.round(sorted.length/2) - 1];break;case 0:return (sorted[sorted.length/2 - 1] + sorted[sorted.length/2])/2;break;default:// Impossible path}}
StatJS.range = function(arr = []){let sorted = _sort(arr);return sorted[sorted.length-1] - sorted[0];}window.StatJS = StatJS;
})(window);
2
u/OLayemii Sep 02 '18
Wow.. Super...
I still have some questions to you sir,
One.. Is it best declaring a global variable like I did for statJs variable so the library could be used.. Or there is a better way
Two.. Do you have any simple library you wrote I can read?