word_histogram.js revision 815:8c53a58a5b72
1153838Sdfr#nashorn word histogram of a file 2153838Sdfr 3153838Sdfr/* 4153838Sdfr * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. 5153838Sdfr * 6153838Sdfr * Redistribution and use in source and binary forms, with or without 7153838Sdfr * modification, are permitted provided that the following conditions 8153838Sdfr * are met: 9153838Sdfr * 10153838Sdfr * - Redistributions of source code must retain the above copyright 11153838Sdfr * notice, this list of conditions and the following disclaimer. 12153838Sdfr * 13153838Sdfr * - Redistributions in binary form must reproduce the above copyright 14153838Sdfr * notice, this list of conditions and the following disclaimer in the 15153838Sdfr * documentation and/or other materials provided with the distribution. 16153838Sdfr * 17153838Sdfr * - Neither the name of Oracle nor the names of its 18153838Sdfr * contributors may be used to endorse or promote products derived 19153838Sdfr * from this software without specific prior written permission. 20153838Sdfr * 21153838Sdfr * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 22153838Sdfr * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 23153838Sdfr * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 24153838Sdfr * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 25153838Sdfr * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 26153838Sdfr * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 27153838Sdfr * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 28153838Sdfr * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 29153838Sdfr * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 30153838Sdfr * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 31153838Sdfr * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32153838Sdfr */ 33153838Sdfr 34153838Sdfr/* 35153838Sdfr * This example demonstrates how to print word histogram 36153838Sdfr * of a given text file using regex, array and JSON 37153838Sdfr * functions. 38153838Sdfr */ 39153838Sdfr 40153838Sdfrif (arguments.length < 1) { 41153838Sdfr print("Usage: jjs -scripting word_histogram.js -- <file>"); 42153838Sdfr exit(1); 43153838Sdfr} 44 45var obj = {}; 46 47readFully(arguments[0]). 48 split(/[^\w+]/). 49 forEach(function(x) 50 (x in obj? obj[x]++ : obj[x] = 1)); 51 52print(JSON.stringify(obj)); 53 54