123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- 'use strict';
- const OneDataSet = require('./hypothesis/one-data-set.js');
- const TwoDataSet = require('./hypothesis/two-data-set.js');
- const Welch = require('./hypothesis/welch.js');
- const Summary = require('summary');
- const ALTERNATIVE_MAP = Object.assign(Object.create(null), {
- 'not equal': 0,
- 'less': -1,
- 'greater': 1
- });
- function isSummary(data) {
- return data && (typeof data.mean === 'function' &&
- typeof data.variance === 'function' &&
- typeof data.size === 'function');
- }
- function isCalculated(data) {
- return data && (typeof data.mean === 'number' &&
- typeof data.variance === 'number' &&
- typeof data.size === 'number');
- }
- function isCompatible(structure) {
- return Array.isArray(structure) ||
- isSummary(structure) ||
- isCalculated(structure);
- }
- function toData(data) {
- if (Array.isArray(data) || isSummary(data)) {
- const summary = isSummary(data) ? data : new Summary(data);
- return {
- mean: summary.mean(),
- variance: summary.variance(),
- size: summary.size()
- };
- } else {
- return data;
- }
- }
- function hypothesis(left, right, options) {
-
- if (!isCompatible(left)) {
- throw new TypeError(
- 'left value in hypothesis test must be an array or data summary'
- );
- }
- if (!isCompatible(right)) {
- options = right;
- right = undefined;
- }
-
- options = Object.assign({
- mu: 0,
- varEqual: false,
- alpha: 0.05,
- alternative: 'not equal'
- }, options);
-
- options.alternative = ALTERNATIVE_MAP[options.alternative];
-
- if (typeof options.mu !== 'number') {
- throw new TypeError('mu option must be a number');
- }
-
- if (typeof options.varEqual !== 'boolean') {
- throw new TypeError('varEqual option must be a boolean');
- }
-
- if (typeof options.alpha !== 'number') {
- throw new TypeError('alpha option must be a number');
- }
- if (options.alpha >= 1) {
- throw new RangeError('alpha must be below 1.0');
- }
-
- if (typeof options.alternative === 'undefined') {
- throw new Error('alternative must be either "not equal", "less" or "greater"');
- }
-
- if (isCompatible(right)) {
- if (options.varEqual) {
- return new TwoDataSet(toData(left), toData(right), options);
- } else {
- return new Welch(toData(left), toData(right), options);
- }
- } else {
- return new OneDataSet(toData(left), options);
- }
- }
- module.exports = hypothesis;
|