Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

initial implementation

  • Loading branch information...
commit dc709c9d3ea9505126eec9829565eab48c2c123a 1 parent 0684e54
@tj tj authored
Showing with 105 additions and 5 deletions.
  1. +1 −0  .gitignore
  2. +12 −0 examples/simple.js
  3. +85 −0 index.js
  4. +7 −5 package.json
View
1  .gitignore
@@ -0,0 +1 @@
+node_modules/
View
12 examples/simple.js
@@ -0,0 +1,12 @@
+
+var histogram = require('..');
+
+var data = {
+ ferrets: 15,
+ cats: 6,
+ dogs: 2,
+ koalas: 0
+};
+
+console.log();
+console.log(histogram(data));
View
85 index.js
@@ -0,0 +1,85 @@
+
+/**
+ * Module dependencies.
+ */
+
+var fmt = require('printf');
+
+/**
+ * Expose `histogram()`.
+ */
+
+module.exports = histogram;
+
+/**
+ * Return ascii histogram of `data`.
+ *
+ * @param {Object} data
+ * @param {Object} [opts]
+ * @return {String}
+ * @api public
+ */
+
+function histogram(data, opts) {
+ opts = opts || {};
+
+ // options
+
+ var width = opts.width || 60;
+
+ // normalize data
+
+ var data = toArray(data).sort(descending);
+ var maxKey = max(data.map(function(d){ return d.key.length }));
+ var maxVal = max(data.map(function(d){ return d.val }));
+ var str = '';
+
+ // blah blah histo
+
+ for (var i = 0; i < data.length; i++) {
+ var d = data[i];
+ var p = d.val / maxVal;
+ var shown = Math.round(width * p);
+ var blank = width - shown
+ var bar = Array(shown + 1).join('#');
+ bar += Array(blank + 1).join(' ');
+ str += fmt(' %*s | %s | %s\n', d.key, maxKey, bar, d.val);
+ }
+
+ return str;
+}
+
+/**
+ * Sort descending.
+ */
+
+function descending(a, b) {
+ return b.val - a.val;
+}
+
+/**
+ * Return max in array.
+ */
+
+function max(data) {
+ var n = data[0];
+
+ for (var i = 1; i < data.length; i++) {
+ n = data[i] > n ? data[i] : n;
+ }
+
+ return n;
+}
+
+/**
+ * Turn object into an array.
+ */
+
+function toArray(obj) {
+ return Object.keys(obj).map(function(key){
+ return {
+ key: key,
+ val: obj[key]
+ }
+ })
+}
View
12 package.json
@@ -1,13 +1,15 @@
{
- "name": "<name>",
+ "name": "cli-histogram",
"version": "0.0.1",
- "repository": "visionmedia/<name>",
+ "repository": "visionmedia/node-cli-histogram",
"description": "",
"keywords": [],
- "dependencies": {},
+ "dependencies": {
+ "printf": "~0.1.2"
+ },
"devDependencies": {
"mocha": "*",
- "should": "*"
+ "should": "*"
},
"license": "MIT"
-}
+}
Please sign in to comment.
Something went wrong with that request. Please try again.