UNPKG

locutus

Version:

Locutus other languages' standard libraries to JavaScript for fun and educational purposes

24 lines (23 loc) 1.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mad = mad; const _stats_ts_1 = require("../_helpers/_stats.js"); function mad(x, center, constant = 1.4826, low = false, high = false) { // discuss at: https://locutus.io/r/mad/ // parity verified: R 4.4 // original by: Kevin van Zonneveld (https://kvz.io) // note 1: Returns R's median absolute deviation for a plain numeric vector. // example 1: mad([1, 2, 3, 4]) // returns 1: 1.4826 // example 2: mad([1, 2, 4, 8], 3, 1) // returns 2: 1.5 // example 3: mad([1, 2, 4, 8], 3, 2) // returns 3: 3 if (low && high) { throw new Error("mad() 'low' and 'high' cannot both be true"); } const values = (0, _stats_ts_1.sortedRNumbers)(x, 'mad'); const centerValue = center === undefined ? (0, _stats_ts_1.medianOfSorted)(values) : (0, _stats_ts_1.toRNumber)(center, 'mad'); const deviations = values.map((value) => Math.abs(value - centerValue)).sort((left, right) => left - right); return (0, _stats_ts_1.toRNumber)(constant, 'mad') * (0, _stats_ts_1.medianOfSorted)(deviations, low, high); }