Skip to content

Instantly share code, notes, and snippets.

@flesch
Last active July 6, 2019 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flesch/34e4f906939ee1bafc74b82e64d4cc48 to your computer and use it in GitHub Desktop.
Save flesch/34e4f906939ee1bafc74b82e64d4cc48 to your computer and use it in GitHub Desktop.
📈 Calculate a “Net Promoter Score” from an array of integers. (Array.reduce)

@flesch/net-promoter-score

Calculate a “Net Promoter Score” from an array of integers.

Install

$ npm install --save gist:34e4f906939ee1bafc74b82e64d4cc48

Usage

const nps = require('@flesch/net-promoter-score');

const score = nps([10, 9, 10, 8, 7, 5, 6, 9, 10]);

console.log(score); // => 33

0(n)

module.exports = (ratings) => {
const totalRatings = ratings.length;
if (totalRatings) {
const reduceRatings = ({ promoters, detractors }, rating) => {
if (rating >= 0 && rating <= 10) {
return {
promoters: rating >= 9 ? ++promoters : promoters,
detractors: rating <= 6 ? ++detractors : detractors,
};
}
return { promoters, detractors };
};
const { promoters, detractors } = ratings.reduce(reduceRatings, { promoters: 0, detractors: 0 });
return Math.round((promoters / totalRatings - detractors / totalRatings) * 100);
}
return 0;
};
{
"name": "@flesch/net-promoter-score",
"description": "Calculate a \"Net Promoter Score\" from an array of integers",
"homepage": "https://gist.github.com/flesch/34e4f906939ee1bafc74b82e64d4cc48",
"version": "1.0.0",
"main": "index.js",
"author": {
"email": "john@fles.ch",
"name": "John Flesch",
"url": "https://fles.ch"
},
"repository": {
"type": "git",
"url": "git+https://gist.github.com/flesch/34e4f906939ee1bafc74b82e64d4cc48.git"
},
"files": ["index.js"],
"license": "MIT"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment