├── .gitattributes ├── .npmrc ├── .travis.yml ├── .editorconfig ├── .verb.md ├── .gitignore ├── example.js ├── LICENSE ├── package.json ├── test.js ├── index.js ├── .github └── contributing.md ├── .eslintrc.json └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | os: 3 | - linux 4 | - osx 5 | language: node_js 6 | node_js: 7 | - node 8 | - '7' 9 | - '6' 10 | - '5' 11 | - '4' 12 | - '0.12' 13 | - '0.10' 14 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | indent_size = 2 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [{**/{actual,fixtures,expected,templates}/**,*.md}] 12 | trim_trailing_whitespace = false 13 | insert_final_newline = false -------------------------------------------------------------------------------- /.verb.md: -------------------------------------------------------------------------------- 1 | ## Usage 2 | 3 | ```js 4 | var sma = require('{%= name %}'); 5 | ``` 6 | 7 | ## API 8 | {%= apidocs('index.js') %} 9 | 10 | ## Attribution 11 | 12 | Thanks to [@jonschlinkert](https://github.com/jonschlinkert) for simplifying the algorithm. For more moving average modules checkout the [related projects](#related-projects) below. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # always ignore files 2 | *.DS_Store 3 | *.sublime-* 4 | 5 | # test related, or directories generated by tests 6 | test/actual 7 | actual 8 | coverage 9 | .nyc* 10 | 11 | # npm 12 | node_modules 13 | npm-debug.log 14 | 15 | # yarn 16 | yarn.lock 17 | yarn-error.log 18 | 19 | # misc 20 | _gh_pages 21 | _draft 22 | _drafts 23 | bower_components 24 | vendor 25 | temp 26 | tmp 27 | TODO.md 28 | 29 | examples/*/dist 30 | examples/*/site 31 | -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var sma = require('./'); 4 | 5 | // `size` of 4 6 | console.log('sma([1, 2, 3, 4, 5, 6, 7, 8, 9], 4);'); 7 | console.log(sma([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)); 8 | console.log(); 9 | 10 | // `size` default to the length of the list 11 | console.log('sma([1, 2, 3, 4, 5]);'); 12 | console.log(sma([1, 2, 3, 4, 5])); 13 | console.log(); 14 | 15 | // custom format function 16 | console.log('sma([1, 2, 3, 4, 5, 6, 7, 8, 9], 4, function(n) { return n.toFixed(5); });'); 17 | console.log(sma([1, 2, 3, 4, 5, 6, 7, 8, 9], 4, function(n) { return n.toFixed(5); })); 18 | console.log(); 19 | 20 | console.log('sma([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10], 3);'); 21 | console.log(sma([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10], 3)); 22 | console.log(); 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Brian Woodward 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sma", 3 | "description": "Calculate the simple moving average of an array.", 4 | "version": "0.1.1", 5 | "homepage": "https://github.com/doowb/sma", 6 | "author": "Brian Woodward (https://doowb.com)", 7 | "repository": "doowb/sma", 8 | "bugs": { 9 | "url": "https://github.com/doowb/sma/issues" 10 | }, 11 | "license": "MIT", 12 | "files": [ 13 | "index.js" 14 | ], 15 | "main": "index.js", 16 | "engines": { 17 | "node": ">=0.10.0" 18 | }, 19 | "scripts": { 20 | "test": "mocha" 21 | }, 22 | "keywords": [ 23 | "arr", 24 | "arr-average", 25 | "arr-avg", 26 | "array", 27 | "array-average", 28 | "array-avg", 29 | "average", 30 | "average-arr", 31 | "avg", 32 | "avg-arr", 33 | "avg-array", 34 | "floating", 35 | "moving", 36 | "rolling", 37 | "simple", 38 | "simple-floating-average", 39 | "simple-floating-avg", 40 | "simple-moving-average", 41 | "simple-moving-avg", 42 | "simple-rolling-average", 43 | "simple-rolling-avg", 44 | "sma" 45 | ], 46 | "devDependencies": { 47 | "gulp-format-md": "^0.1.12", 48 | "mocha": "^3.2.0" 49 | }, 50 | "verb": { 51 | "toc": false, 52 | "layout": "default", 53 | "tasks": [ 54 | "readme" 55 | ], 56 | "plugins": [ 57 | "gulp-format-md" 58 | ], 59 | "lint": { 60 | "reflinks": true 61 | }, 62 | "related": { 63 | "list": [ 64 | "exponential-moving-average" 65 | ] 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | require('mocha'); 4 | var assert = require('assert'); 5 | var sma = require('./'); 6 | 7 | describe('sma', function() { 8 | it('should export a function', function() { 9 | assert.equal(typeof sma, 'function'); 10 | }); 11 | 12 | it('should throw an error when invalid args are passed', function(cb) { 13 | try { 14 | sma(); 15 | cb(new Error('expected an error')); 16 | } catch (err) { 17 | assert(err); 18 | assert.equal(err.message, 'expected first argument to be an array'); 19 | cb(); 20 | } 21 | }); 22 | 23 | it('should calculate the simple moving average for an array of integers', function() { 24 | assert.deepEqual(sma([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3), [2, 3, 4, 5, 6, 7, 8, 9]); 25 | }); 26 | 27 | it('should calculate the simple moving average for an array of decimals', function() { 28 | var expected = ['2.20', '3.30', '4.40', '5.50', '6.60', '7.70', '8.80', '9.60']; 29 | assert.deepEqual(sma([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10], 3), expected); 30 | }); 31 | 32 | it('should calculate the average for an entire array when range is not passed.', function() { 33 | assert.deepEqual(sma([1, 2, 3]), [2]); 34 | }); 35 | 36 | it('should use a custom format function', function() { 37 | var format = function(n) { 38 | return n.toFixed(5); 39 | }; 40 | var expected = ['2.50000', '3.50000', '4.50000', '5.50000', '6.50000', '7.50000']; 41 | assert.deepEqual(sma([1, 2, 3, 4, 5, 6, 7, 8, 9], 4, format), expected); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Calculate the simple moving average of an array. A new array is returned with the average 5 | * of each range of elements. A range will only be calculated when it contains enough elements to fill the range. 6 | * 7 | * ```js 8 | * console.log(sma([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)); 9 | * //=> [ '2.50', '3.50', '4.50', '5.50', '6.50', '7.50' ] 10 | * //=> │ │ │ │ │ └─(6+7+8+9)/4 11 | * //=> │ │ │ │ └─(5+6+7+8)/4 12 | * //=> │ │ │ └─(4+5+6+7)/4 13 | * //=> │ │ └─(3+4+5+6)/4 14 | * //=> │ └─(2+3+4+5)/4 15 | * //=> └─(1+2+3+4)/4 16 | * ``` 17 | * @param {Array} `arr` Array of numbers to calculate. 18 | * @param {Number} `range` Size of the window to use to when calculating the average for each range. Defaults to array length. 19 | * @param {Function} `format` Custom format function called on each calculated average. Defaults to `n.toFixed(2)`. 20 | * @return {Array} Resulting array of averages. 21 | * @api public 22 | */ 23 | 24 | function sma(arr, range, format) { 25 | if (!Array.isArray(arr)) { 26 | throw TypeError('expected first argument to be an array'); 27 | } 28 | 29 | var fn = typeof format === 'function' ? format : toFixed; 30 | var num = range || arr.length; 31 | var res = []; 32 | var len = arr.length + 1; 33 | var idx = num - 1; 34 | while (++idx < len) { 35 | res.push(fn(avg(arr, idx, num))); 36 | } 37 | return res; 38 | } 39 | 40 | /** 41 | * Create an average for the specified range. 42 | * 43 | * ```js 44 | * console.log(avg([1, 2, 3, 4, 5, 6, 7, 8, 9], 5, 4)); 45 | * //=> 3.5 46 | * ``` 47 | * @param {Array} `arr` Array to pull the range from. 48 | * @param {Number} `idx` Index of element being calculated 49 | * @param {Number} `range` Size of range to calculate. 50 | * @return {Number} Average of range. 51 | */ 52 | 53 | function avg(arr, idx, range) { 54 | return sum(arr.slice(idx - range, idx)) / range; 55 | } 56 | 57 | /** 58 | * Calculate the sum of an array. 59 | * @param {Array} `arr` Array 60 | * @return {Number} Sum 61 | */ 62 | 63 | function sum(arr) { 64 | var len = arr.length; 65 | var num = 0; 66 | while (len--) num += Number(arr[len]); 67 | return num; 68 | } 69 | 70 | /** 71 | * Default format method. 72 | * @param {Number} `n` Number to format. 73 | * @return {String} Formatted number. 74 | */ 75 | 76 | function toFixed(n) { 77 | return n.toFixed(2); 78 | } 79 | 80 | /** 81 | * Expose `sma` 82 | */ 83 | 84 | module.exports = sma; 85 | -------------------------------------------------------------------------------- /.github/contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to sma 2 | 3 | First and foremost, thank you! We appreciate that you want to contribute to sma, your time is valuable, and your contributions mean a lot to us. 4 | 5 | **What does "contributing" mean?** 6 | 7 | Creating an issue is the simplest form of contributing to a project. But there are many ways to contribute, including the following: 8 | 9 | - Updating or correcting documentation 10 | - Feature requests 11 | - Bug reports 12 | 13 | If you'd like to learn more about contributing in general, the [Guide to Idiomatic Contributing](https://github.com/jonschlinkert/idiomatic-contributing) has a lot of useful information. 14 | 15 | **Showing support for sma** 16 | 17 | Please keep in mind that open source software is built by people like you, who spend their free time creating things the rest the community can use. 18 | 19 | Don't have time to contribute? No worries, here are some other ways to show your support for sma: 20 | 21 | - star the [project](https://github.com/doowb/sma) 22 | - tweet your support for sma 23 | 24 | ## Issues 25 | 26 | ### Before creating an issue 27 | 28 | Please try to determine if the issue is caused by an underlying library, and if so, create the issue there. Sometimes this is difficult to know. We only ask that you attempt to give a reasonable attempt to find out. Oftentimes the readme will have advice about where to go to create issues. 29 | 30 | Try to follow these guidelines 31 | 32 | - **Investigate the issue**: 33 | - **Check the readme** - oftentimes you will find notes about creating issues, and where to go depending on the type of issue. 34 | - Create the issue in the appropriate repository. 35 | 36 | ### Creating an issue 37 | 38 | Please be as descriptive as possible when creating an issue. Give us the information we need to successfully answer your question or address your issue by answering the following in your issue: 39 | 40 | - **version**: please note the version of sma are you using 41 | - **extensions, plugins, helpers, etc** (if applicable): please list any extensions you're using 42 | - **error messages**: please paste any error messages into the issue, or a [gist](https://gist.github.com/) 43 | 44 | ## Above and beyond 45 | 46 | Here are some tips for creating idiomatic issues. Taking just a little bit extra time will make your issue easier to read, easier to resolve, more likely to be found by others who have the same or similar issue in the future. 47 | 48 | - read the [Guide to Idiomatic Contributing](https://github.com/jonschlinkert/idiomatic-contributing) 49 | - take some time to learn basic markdown. This [markdown cheatsheet](https://gist.github.com/jonschlinkert/5854601) is super helpful, as is the GitHub guide to [basic markdown](https://help.github.com/articles/markdown-basics/). 50 | - Learn about [GitHub Flavored Markdown](https://help.github.com/articles/github-flavored-markdown/). And if you want to really go above and beyond, read [mastering markdown](https://guides.github.com/features/mastering-markdown/). 51 | - use backticks to wrap code. This ensures that code will retain its format, making it much more readable to others 52 | - use syntax highlighting by adding the correct language name after the first "code fence" 53 | 54 | 55 | [node-glob]: https://github.com/isaacs/node-glob 56 | [micromatch]: https://github.com/jonschlinkert/micromatch 57 | [so]: http://stackoverflow.com/questions/tagged/sma -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "ecmaFeatures": { 3 | "modules": true, 4 | "experimentalObjectRestSpread": true 5 | }, 6 | 7 | "env": { 8 | "browser": false, 9 | "es6": true, 10 | "node": true, 11 | "mocha": true 12 | }, 13 | 14 | "globals": { 15 | "document": false, 16 | "navigator": false, 17 | "window": false 18 | }, 19 | 20 | "rules": { 21 | "accessor-pairs": 2, 22 | "arrow-spacing": [2, { "before": true, "after": true }], 23 | "block-spacing": [2, "always"], 24 | "brace-style": [2, "1tbs", { "allowSingleLine": true }], 25 | "comma-dangle": [2, "never"], 26 | "comma-spacing": [2, { "before": false, "after": true }], 27 | "comma-style": [2, "last"], 28 | "constructor-super": 2, 29 | "curly": [2, "multi-line"], 30 | "dot-location": [2, "property"], 31 | "eol-last": 2, 32 | "eqeqeq": [2, "allow-null"], 33 | "generator-star-spacing": [2, { "before": true, "after": true }], 34 | "handle-callback-err": [2, "^(err|error)$" ], 35 | "indent": [2, 2, { "SwitchCase": 1 }], 36 | "key-spacing": [2, { "beforeColon": false, "afterColon": true }], 37 | "keyword-spacing": [2, { "before": true, "after": true }], 38 | "new-cap": [2, { "newIsCap": true, "capIsNew": false }], 39 | "new-parens": 2, 40 | "no-array-constructor": 2, 41 | "no-caller": 2, 42 | "no-class-assign": 2, 43 | "no-cond-assign": 2, 44 | "no-const-assign": 2, 45 | "no-control-regex": 2, 46 | "no-debugger": 2, 47 | "no-delete-var": 2, 48 | "no-dupe-args": 2, 49 | "no-dupe-class-members": 2, 50 | "no-dupe-keys": 2, 51 | "no-duplicate-case": 2, 52 | "no-empty-character-class": 2, 53 | "no-eval": 2, 54 | "no-ex-assign": 2, 55 | "no-extend-native": 2, 56 | "no-extra-bind": 2, 57 | "no-extra-boolean-cast": 2, 58 | "no-extra-parens": [2, "functions"], 59 | "no-fallthrough": 2, 60 | "no-floating-decimal": 2, 61 | "no-func-assign": 2, 62 | "no-implied-eval": 2, 63 | "no-inner-declarations": [2, "functions"], 64 | "no-invalid-regexp": 2, 65 | "no-irregular-whitespace": 2, 66 | "no-iterator": 2, 67 | "no-label-var": 2, 68 | "no-labels": 2, 69 | "no-lone-blocks": 2, 70 | "no-mixed-spaces-and-tabs": 2, 71 | "no-multi-spaces": 2, 72 | "no-multi-str": 2, 73 | "no-multiple-empty-lines": [2, { "max": 1 }], 74 | "no-native-reassign": 0, 75 | "no-negated-in-lhs": 2, 76 | "no-new": 2, 77 | "no-new-func": 2, 78 | "no-new-object": 2, 79 | "no-new-require": 2, 80 | "no-new-wrappers": 2, 81 | "no-obj-calls": 2, 82 | "no-octal": 2, 83 | "no-octal-escape": 2, 84 | "no-proto": 0, 85 | "no-redeclare": 2, 86 | "no-regex-spaces": 2, 87 | "no-return-assign": 2, 88 | "no-self-compare": 2, 89 | "no-sequences": 2, 90 | "no-shadow-restricted-names": 2, 91 | "no-spaced-func": 2, 92 | "no-sparse-arrays": 2, 93 | "no-this-before-super": 2, 94 | "no-throw-literal": 2, 95 | "no-trailing-spaces": 0, 96 | "no-undef": 2, 97 | "no-undef-init": 2, 98 | "no-unexpected-multiline": 2, 99 | "no-unneeded-ternary": [2, { "defaultAssignment": false }], 100 | "no-unreachable": 2, 101 | "no-unused-vars": [2, { "vars": "all", "args": "none" }], 102 | "no-useless-call": 0, 103 | "no-with": 2, 104 | "one-var": [0, { "initialized": "never" }], 105 | "operator-linebreak": [0, "after", { "overrides": { "?": "before", ":": "before" } }], 106 | "padded-blocks": [0, "never"], 107 | "quotes": [2, "single", "avoid-escape"], 108 | "radix": 2, 109 | "semi": [2, "always"], 110 | "semi-spacing": [2, { "before": false, "after": true }], 111 | "space-before-blocks": [2, "always"], 112 | "space-before-function-paren": [2, "never"], 113 | "space-in-parens": [2, "never"], 114 | "space-infix-ops": 2, 115 | "space-unary-ops": [2, { "words": true, "nonwords": false }], 116 | "spaced-comment": [0, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!", ","] }], 117 | "use-isnan": 2, 118 | "valid-typeof": 2, 119 | "wrap-iife": [2, "any"], 120 | "yoda": [2, "never"] 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sma [![NPM version](https://img.shields.io/npm/v/sma.svg?style=flat)](https://www.npmjs.com/package/sma) [![NPM monthly downloads](https://img.shields.io/npm/dm/sma.svg?style=flat)](https://npmjs.org/package/sma) [![NPM total downloads](https://img.shields.io/npm/dt/sma.svg?style=flat)](https://npmjs.org/package/sma) [![Linux Build Status](https://img.shields.io/travis/doowb/sma.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/sma) 2 | 3 | > Calculate the simple moving average of an array. 4 | 5 | Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. 6 | 7 | ## Install 8 | 9 | Install with [npm](https://www.npmjs.com/): 10 | 11 | ```sh 12 | $ npm install --save sma 13 | ``` 14 | 15 | ## Usage 16 | 17 | ```js 18 | var sma = require('sma'); 19 | ``` 20 | 21 | ## API 22 | 23 | ### [sma](index.js#L24) 24 | 25 | Calculate the simple moving average of an array. A new array is returned with the average of each range of elements. A range will only be calculated when it contains enough elements to fill the range. 26 | 27 | **Params** 28 | 29 | * `arr` **{Array}**: Array of numbers to calculate. 30 | * `range` **{Number}**: Size of the window to use to when calculating the average for each range. Defaults to array length. 31 | * `format` **{Function}**: Custom format function called on each calculated average. Defaults to `n.toFixed(2)`. 32 | * `returns` **{Array}**: Resulting array of averages. 33 | 34 | **Example** 35 | 36 | ```js 37 | console.log(sma([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)); 38 | //=> [ '2.50', '3.50', '4.50', '5.50', '6.50', '7.50' ] 39 | //=> │ │ │ │ │ └─(6+7+8+9)/4 40 | //=> │ │ │ │ └─(5+6+7+8)/4 41 | //=> │ │ │ └─(4+5+6+7)/4 42 | //=> │ │ └─(3+4+5+6)/4 43 | //=> │ └─(2+3+4+5)/4 44 | //=> └─(1+2+3+4)/4 45 | ``` 46 | 47 | ## Attribution 48 | 49 | Thanks to [@jonschlinkert](https://github.com/jonschlinkert) for simplifying the algorithm. For more moving average modules checkout the [related projects](#related-projects) below. 50 | 51 | ## About 52 | 53 |
54 | Contributing 55 | 56 | Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). 57 | 58 | Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. 59 | 60 |
61 | 62 |
63 | Running Tests 64 | 65 | Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: 66 | 67 | ```sh 68 | $ npm install && npm test 69 | ``` 70 | 71 |
72 | 73 |
74 | Building docs 75 | 76 | _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ 77 | 78 | To generate the readme, run the following command: 79 | 80 | ```sh 81 | $ npm install -g verbose/verb#dev verb-generate-readme && verb 82 | ``` 83 | 84 |
85 | 86 | ### Related projects 87 | 88 | You might also be interested in these projects: 89 | 90 | [exponential-moving-average](https://www.npmjs.com/package/exponential-moving-average): Calculate an exponential moving average from an array of numbers. | [homepage](https://github.com/jonschlinkert/exponential-moving-average "Calculate an exponential moving average from an array of numbers.") 91 | 92 | ### Author 93 | 94 | **Brian Woodward** 95 | 96 | * [GitHub Profile](https://github.com/doowb) 97 | * [Twitter Profile](https://twitter.com/doowb) 98 | * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) 99 | 100 | ### License 101 | 102 | Copyright © 2018, [Brian Woodward](https://doowb.com). 103 | Released under the [MIT License](LICENSE). 104 | 105 | *** 106 | 107 | _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on September 12, 2018._ --------------------------------------------------------------------------------