Skip to content

Instantly share code, notes, and snippets.

@michel-zimmer
Created November 16, 2016 09:29

Revisions

  1. Michel Zimmer created this gist Nov 16, 2016.
    38 changes: 38 additions & 0 deletions lpd.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    #!/usr/bin/env node

    const ignorecase = true;
    const include = "abcdefghijklmnopqrstuvwxyz";

    function lpd(data) {
    // prepare
    let distribution = {};
    let sum = 0;
    include.split('').forEach(c => distribution[c] = 0);

    // ignore case
    if (ignorecase) {
    data = data.toLowerCase();
    }

    // count
    data.split('').forEach(c => {
    if (include.indexOf(c) >= 0) {
    distribution[c]++;
    sum++;
    }
    });

    // calculate and round percentage
    include.split('').forEach(c => distribution[c] = Math.round(distribution[c] * 10000 / sum) / 100);

    return distribution;
    }

    // use stdin and stout when called directly
    if (require.main === module) {
    let data = "";
    process.openStdin().on('data', (chunk) => data += chunk).on('end', () => console.log(JSON.stringify(lpd(data), null, 2)));
    } else {
    // otherwise export as module
    exports = lpd;
    }