Posts

Ways to iterate array items in JavaScript

A few days ago i introduced arrays and described what they are and how their elements can be iterated in JavaScript using 'for loop' There many other ways to iterate arrays namely Array.forEach, Array.map, var array = ['eat', 'code', 'sleep'] Using forEach array.forEach(function(value, index){     console.log(index + ': '+ value) }) // result expected // 0: "eat" // 1: "code" // 2: "sleep" Using Array.map array.map(function(value, index){     console.log(index + ': '+ value) }) // result expected // 0: "eat" // 1: "code" // 2: "sleep" It's a wrapp

Lexer and tokenizer for robots.txt in JavaScript

Introduction I'm sharing how i made lexer and tokenizer for robots.txt in JavaScript Reasons and motives I'm using it in the Nodejs environment of course so it's server side it's part of another project I'm doing. How it's done robots.txt files contain one directive per line inform of Key: value Take for instance User-agent: Googlebot/{version} Disallow: {path} Path the disallowed location it may included wildcards ie "*" or "/" its not a good idea to consume them raw without validation And version number is ignored to make targeting bots easy i guess Steps taken by the lexer Splitting text into an array containing data from the robots.txt file line by line given it's provided with an input looking like this User-agent: Googlebot/{version} Disallow: {path} It may return something that's like this [User-agent: Googlebot/{version}, Disallow: {path}] Almost there. after that next step is to remove c...

Removing bash.sh #hash comments from a string using regEx in JavaScript

Last night i was looking for a method to remove comments from a robots.txt file containing contents of form below `# robots.txt user-agent Disallow:` Or a more practical format obtained by splitting the robots.txt file line by line. ["# robots.txt", "user-agent", "Disallow:"] every element of the array is a string representing a single line of text from a robots.txt plain text file. Regular expression I used regular expression to strip out the unwanted text until the end of the line however it's not limited to robots.txt it works perfectly with bash.sh files as well. Example var string = "Disallow / #deny bots" string.replace(/#.*$/, "") // returns  Disallow / It simply strip's off all characters after the hash character until the end of the line.

How to iterate array elements using 'for loop' in JavaScript

JavaScript arrays are similar to arrays in c and in c like programming languages such as php among others In JavaScript arrays are simply collections of elements for instance Objects Numbers or other Arrays Declaring an array An array may be declared using the array constructor for instance const array = new Array() or as const array = [] Iterating an array using 'for' loop This is the implest and most common method to iterate an array is by using the 'for loop' am sure you're familiar with the syntax. take for Instance you want to iterate an array of integers and print each one of them. var ints = [1, 2, 3, 4] To iterate ints using for loop. for (var i = 0; i < ints.length; i++){         console.log(ints[i]) } // output will be // 1 // 2 // 3 // 4 In between the parentheses they are three procedures in three segments separated by colons first segment declares var i an index which gets incriminated in the third segment as long as...

How to use canvas context rect method for drawing rectangles

canvas context rect method does as it says. It's used for drawing a rectangle on a canvas context Parameters context.rect(positionX, positionY, Width, Height) PositionX specifies the x coordinate at which the rectangle should be drawn at on the context PositionY specifies the y coordinate at which the rectangle should be drawn at on the context Width specifies the width of the rectangle Height specifies the height of the rectangle Stroking and filling the rectangle In order for the rectangle to be actually visible you have to either stroke it or fill it with a color. Stroke Stroking a rectangle means to draw a line that joins all of it's vertices To specify the fill color you should set it and call stroke to draw context.strokeStyle = "#colors" context.stroke() Fill Similar to srokings filling a rectangle means to paint it's inner bounding box with a specified color context.fillStyle = "#colors" context.fill() Example context.rect...

Install steam locomotive sl using apt

sl or steam locomotive is a commandline application that displays steam locomotive "train" animations aimed to correct users who accidentally enter sl instead of ls.  initials sl stands for Steam Locomotive How to install ls or steam locomotive Assuming you've root privileges and installed apt package manager on your system Type sudo apt-get update sudo apt-get upgrade sudo apt-get install sl To test installation type sl If installation was successful You'll see an ASCII image of a train right in your terminal after few seconds it will stop

JavaScript canvas introduction

Introduction Probably next monday I will post a how to make a snake game clone in a few lines of JavaScript code post don't miss it out subscribe to my email newsletter! What is a canvas I'm sure you've heard of the term somewhere. canvas through their "2d" context allow drawing 2d graphics using a simple JavaScript api You can use a canvas to draw text , lines simple shapes, and images canvas can also be used as a renderer for JavaScript built html5 games "that's were we're going" Example on canvas it draws a rectangle on a canvas context black color by default <html> <canvas id="canvas"></canvas> <script type="text/javascript">         var context = canvas.getContext("2d") // stroke a 100px square at 0, 0 context.rect(0, 0, 100, 100) context. stroke () </script> </html> Save and open it in your browser you should see a square on the top right corner of your bro...

JavaScript spread operator

JavaScript spread operator is a useful operator for manipulation of objects , strings and arrays in JavaScript among others you can you it to effectively copy an object or array expand it or even convert a string into an array of its constituent characters. const chars = ["a", "b", "c"] const name = "John swana" Copying an array using spread operator to copy an array using a spread operator you can do it using the syntax as follows var alphabet = [...chars] And now alphabet contains chars properties alphabet // ["a", "b", "c"] Copying an object using spread operator Similarly you can copy JavaScript objects using spread operator. Take for instance const object = {name:  "John swana", gender: "male"} var user = {...object} user //  {name:  "John swana", gender: "male"} Converting a string into an array Note that you can use String.prototype.split for this...

Installing and using 'cowsay' with fortune

what is 'cowsay'  it's a simple commandline program of a cow which basically prints whatever text argument you pass to it inform of a speech bubble from a ancii cow c:owsay goes hand in hand with another cli programme called fortune it generates text fortune messages which can be easy be tunnelled into cowsay Cowsay is so popular that i decides to write a how to installation post To get started open your commandline terminal and type sudo apt-get update  sudo apt-get upgrade sudo apt-get install cowsay To install another cli app 'fortune' type the following in your terminal sudo apt-get install fortune After installation test fortune by typing in your console fortune // typical response Training is everything.  The peach was once a bitter almond; cauliflower is nothing but cabbage with a college education.                 -- Mark Twain, "Pudd'nhead Wilson's Calendar" To test cowsay type cowsay fo...

JavaScript class getters and setters

Introduction I assume you know heard or at least in someone's code seen JavaScript classes. newly introduced classes are much better than functions if your code requires inheritance of constructors "classes" Brief subintroduction A class can be made using syntax below given cats as an example class chat {     constructor(params) {         this.name = params.name         this.color = params.color     }     meow() {         console.log("meow meows" + this. name)     } } Explanation cat is a class with a constructor and a method named meow note that you can omit the constructor in the above code if you have nothing to initialize Adding Getters getters are a piece of code that retrieve properties of a class in class cat they're no user defined getters JavaScript properties can be retrieved even if you don't use ...