Misc 0 Comments November 17, 2017

WHO WOULD WIN?

Who would win?
 One big curly brace or one hundred tiny semicolons?
WHO WOULD WIN? ONE BIG CURLY BRACE OR 100 TINY SEMICOLONS?

Yesterday I wrote a random JSON data structure generator for my next site Online Random Tools. Here's a quick article about what my thought process was when I was writing it.

1. What's a good name for this function? generateRandomJson sounds good. Let's put it in code:

function generateRandomJson () {

2. So what is a JSON data structure? It's one of number, string, boolean, array or object. So let's put it in code:

var choices = ["number", "string", "boolean", "array", "object"];
var choice = chooseOne(choices);

function chooseOne(choices) {
  return choices[parseInt(Math.random()*choices.length)];
}

3. What is a number? It's an integer or a floating point. Negative or positive. Let's put that in code:

if (choice == "number") {
  return generateRandomNumber();
}

function generateRandomNumber () {
  var maxNum = 2**32;
  var number = Math.random()*maxNum;
  var isInteger = chooseOne([true,false]);
  var isNegative = chooseOne([true,false]);
  
  if (isInteger) number = parseInt(number);
  if (isNegative) number = -number;

  return number;
}

4. What is a string? It's zero or more characters. Let's put it in code:

if (choice == "string") {
  return generateRandomString();
}

function generateRandomString () {
  var alphabet = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

  var maxLength = 100;
  var length = Math.random()*maxLength;
  var string = "";
  for (var i = 0; i < length; i++) {
    string += chooseOne(alphabet);
  }

  return string;
}

5. What is a boolean? It's true or false. Let's put it in code:

if (choice == "boolean") {
  return generateRandomBoolean();
}

function generateRandomBoolean () {
  return chooseOne([true,false]);
}

6. What is an array? It's zero or more of random JSON data structures. Let's put that in code:

if (choice == "array") {
  return generateRandomArray();
}

function generateRandomArray () {
  var maxArrayLength = 10;
  var length = parseInt(Math.random()*maxArrayLength);

  var array = [];  
  for (var i = 0; i < length; i++) {
    array[i] = generateRandomJson();
  }

  return array;
}

7. What is an object? It's zero or more random string keys with random JSON data structures as values. Let's put that in code:

if (choice == "object") {
  return generateRandomObject();
}

function generateRandomObject () {
  var maxObjectKeys = 10;
  var keyCount = parseInt(Math.random()*maxObjectKeys);

  var object = {};  
  for (var i = 0; i < keyCount; i++) {
    var key = generateRandomKeyName();
    object[key] = generateRandomJson();
  }

  return object;
}

function generateRandomKeyName () {
  var maxKeyLength = 10;
  var keyLength = 1 + parseInt(Math.random()*maxKeyLength);
  var randomString = generateRandomString();
  return randomString.substr(0,keyLength)
}

8. And we're done. We've covered all the cases and can close the generateRandomJson function:

}

9. Now let's try it and pretty print it:

var json = generateRandomJson();
console.log(prettyPrintJson(json));

function prettyPrintJson (json) {
  return JSON.stringify(json, null, 2);
}

This function will sometimes cause a stack overflow because we haven't limited the depth of the JSON data structure. We can easily do that by passing maxDepth as an argument and avoiding generating nested JSON substructures when it's 0. There are many more improvements that can be made, such as passing options for max string length, max number to generate, max number of elements per depth level, etc. I've implemented all these in Random JSON Generator online tool that you can try.

function generateRandomJson (maxDepth) {
    var choices = ["number", "string", "boolean", "array", "object"];
    if (maxDepth == 0) {
        choices = ["number", "string", "boolean"];
    }

    var choice = chooseOne(choices);

    function chooseOne(choices) {
        return choices[parseInt(Math.random()*choices.length)];
    }

    if (choice == "number") {
        return generateRandomNumber();
    }
    if (choice == "string") {
        return generateRandomString();
    }
    if (choice == "boolean") {
        return generateRandomBoolean();
    }
    if (choice == "array") {
        return generateRandomArray();
    }
    if (choice == "object") {
        return generateRandomObject();
    }

    function generateRandomNumber () {
        var maxNum = 2**32;
        var number = Math.random()*maxNum;
        var isInteger = chooseOne([true,false]);
        var isNegative = chooseOne([true,false]);

        if (isInteger) number = parseInt(number);
        if (isNegative) number = -number;

        return number;
    }

    function generateRandomString () {
        var alphabet = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

        var maxLength = 100;
        var length = Math.random()*maxLength;
        var string = "";
        for (var i = 0; i < length; i++) {
            string += chooseOne(alphabet);
        }

        return string;
    } 

    function generateRandomBoolean () {
        return chooseOne([true,false]);
    }

    function generateRandomArray () {
        var maxArrayLength = 10;
        var length = parseInt(Math.random()*maxArrayLength);

        var array = [];  
        for (var i = 0; i < length; i++) {
            array[i] = generateRandomJson(maxDepth-1);
        }

        return array;
    }

    function generateRandomObject () {
        var maxObjectKeys = 10;
        var keyCount = parseInt(Math.random()*maxObjectKeys);

        var object = {};  
        for (var i = 0; i < keyCount; i++) {
            var key = generateRandomKeyName();
            object[key] = generateRandomJson(maxDepth-1);
        }

        return object;
    }

    function generateRandomKeyName () {
        var maxKeyLength = 10;
        var keyLength = 1 + parseInt(Math.random()*maxKeyLength);
        var randomString = generateRandomString();
        return randomString.substr(0,keyLength)
    }
}

Now let's generate a random JSON data structure with maxDepth of 5:

var json = generateRandomJson(5);
prettyPrintJson(json);

Success!

I also made a nice UI for this tool. You can play with it here:

Random JSON Generator

Clear thoughts lead to clear code. See you next time!

I just had this idea to illustrate popular computer quotes for Browserling's nerd comic. I asked my illustrator to do it and here's what we made.

There are two major products that came out of Berkeley: LSD and UNIX.
We do not believe this to be a coincidence.

Quote by Jeremy S. Anderson and Steve Aukstakalnis.

BSD Daemon used with permission. (www.mckusick.com/copyright.html)

Always code as if the guy who ends up maintaining your code
will be a violent psychopath who knows where you live.

Quote by John F. Woods.

Computer science is no more about computers than
astronomy is about telescopes.

Quote by Edsger W. Dijkstra.

Lisp isn't a language, it's a building material.

Quote by Alan Kay.

Computers are useless. They can only give you answers.

Quote by Pablo Picasso.

Bonus quote:

Give me the command line and I shall move the world.

Quote by modern day Archimedes.

See you next time!

At Browserling we're building a network of online tools websites. Each site in the network focuses on one and only one tool category. Each tool does one and only one thing. The first three websites in the network are Online CSV Tools, which is all about working with Comma Separated Values data, Online JSON Tools, which is all about working with JSON data, Online XML Tools, which is all about working with XML documents.

Now we're releasing the fourth site.

The fourth site in our network is Online String Tools. Online String Tools is a collection of simple, free and easy to use string manipulation utilities. There are no ads, popups or other garbage. Just string utilities that work in your browser. Load a string and instantly get result.

There will be over 100 tools in this site. So far we've added 40 and it's time to release. We love to release early and often. We'll be adding the remaining tools over next few months.


www.onlineSTRINGtools.com

Here's a list of all string tools so far:

Here are upcoming string tools that we'll be adding over the next few months:

  • Join Strings
  • Replace Multiple Strings
  • Randomize String's Case
  • Invert String's Case
  • Title-case a String
  • Capitalize Words in a String
  • Center a String
  • Right-align a String
  • Left-pad a String
  • Right-pad a String
  • Justify a String
  • Format a Multi-line String
  • Find Number of Letters in a String
  • Find Number of Words in a String
  • Find Number of Lines in a String
  • Find Number of Paragraphs in a String
  • Sort Words in a String
  • Sort Numeric Strings
  • String Frequency Analysis
  • Number Lines in a Multi-line String
  • Add a Prefix to Strings
  • Add a Suffix to Strings
  • Shuffle Words in a String
  • Extract Regex Matches
  • Extract Emails from a String
  • Extract URLs from a String
  • Extract Numbers from a String
  • Generate String Statistics
  • Convert a String to Punycode
  • Convert Punycode to a String
  • Base32-encode a String
  • Base32-decode a String
  • Base58-encode a String
  • Base58-decode a String
  • Base85-encode a String
  • Base85-decode a String
  • UTF8-encode a String
  • UTF8-decode a String
  • UTF16-encode a String
  • UTF16-decode a String
  • UTF32-encode a String
  • UTF32-decode a String
  • IDN-encode a String
  • IDN-decode a String
  • Uuencode a String
  • Uudecode a String
  • Xxencode a String
  • Xxdecode a String
  • HTML-strip a String
  • Convert Spaces to Tabs
  • Convert Tabs to Spaces
  • Convert Spaces to Newlines
  • Convert Newlines to Spaces
  • Remove Accent Characters from a String
  • Remove Duplicate Spaces from a String
  • Remove String Punctuation
  • Printf a String
  • Diff Two Strings
  • Find Levenshtein Distance Between Two Strings
  • Rewrite a String
  • Generate a Zalgo String
  • Generate String Typos
  • Grep a Multi-line String
  • Head a Multi-line String
  • Tail a Multi-line String
  • And more!

The next few sites are onlineIMAGEtools, onlineYAMLtools, onlineTSVtools, onlinePDFtools, onlineBROWSERtools, onlineCRYPTOtools, and then 25 more.

If you like what I'm doing you can subscribe to my blog and/or follow me on twitter and/or follow browserling on twitter and/or do nothing.

See you next time!

At Browserling we're building a network of online tools websites. Each site in the network focuses on one and only one tool category. Each tool does one and only one thing. The first two websites in the network are Online CSV Tools for working with CSV (Comma Separated Values) files and Online JSON Tools for working with JSON data structures.

Now we just finished the third site.

The third site in our network is Online XML Tools. Online XML Tools is a collection of simple, free and easy to use XML utilities. There are no ads, popups or other garbage. Just XML utilities that work in your browser. Load XML and instantly get result.


www.onlineXMLtools.com

Here's a list of all XML tools on this website:

Here are upcoming XML tools that we'll be adding to this site:

  • Syntax Highlight XML
  • Display XML Document Statistics
  • Compare Two XML Files

The next few sites are onlineSTRINGtools (now live!) with hundreds of tiny string utilities. Then onlineIMAGEtools, onlineYAMLtools, onlineTSVtools, onlinePDFtools, onlineBROWSERtools, onlineCRYPTOtools, and then 30 more sites over the next 3 years.

If you like what I'm doing you can subscribe to my blog and/or follow me on twitter and/or follow browserling on twitter and/or do nothing.

See you next time!