Friday, September 25, 2015

Hand out - Javascript - Regular Expression

Introduction:
This post is to know regular expression, see usage in sample examples using JavaScript. Plan is to update this post every time a regular expression is solved. Considering this as a quick hand out to refresh memories as well as a list regular expression which are encountered at some point of development life time.


What is regular expression:
A regular expression is a sequence of characters that forms a search pattern to match a combination in strings. In JavaScript regular expression is an object which can be created explicitly or implicitly.

Regular expression creation

Option-01: implicit way -

var regExp = /[0-9]/;

Option-02: explicit way- 

var regExp = new RegExp('[0-9]');

Note: better to use option-01 as option-02 has implication on execution speed.


Various patterns:

1. Direct match - /direct/. This pattern will find a match in string 'Looking for a direct match' but not in 'Misspelled the word diract'.

2. Special characters - 

PatternMeaning/exampleMatching StringNon matching string
\Escape character

^matches beginning of input. /^A/ AppleBanana
$matches end of input. /a$/Bananaapple
*matches preceding expression 0 or many times. /p*/- Apple
- Orange
+matches preceding expression 1 or many times. /p+/- Apple
- Peach
- Orange, any string not have p in it
?matches preceding expression 0 or 1 times. /p?/- Peach
- Pear
- Apple
()matches and remembers it. Also called capturing parentheses. /(p)/
Table Cell
(?:)Matches 'x' but does not remember the match

(?=)Look ahead. /A(?=p)/. Match only if A (capital) followed by p. - Apple
- Apricot
- Avocado
- apple
(?!)negated look ahead. /A(?!p)/. Match only if A (capital) doesn't follow by p. - Avocado
- apple
- Apple
- Apricot
 |matches either one. /A|a/.- Apple
- apple
- one
- Two
- Three
{}matches exactly that many occurrences. /p{2}/. Has to be positive number.- Apple
- Pepper 
- Apricot
- Pear
- Peach
{ , }matches at least first and at most second. /p{1,2}/.- Apple
- Pepper
- Apricot
- Pear
- Peach
[]Character set. /[Pe|pe]/.- Pepper
- Pear
- Peach
- Apricot
- Apple
[^ ]Negated character set. /[^pe]/.- Pear
- Peach
- Apple
- Apricot
- Pepper
\bmatches word boundary where word character not preceded or followed wit any character. /\bp/- pear
- peach
-Apple
\dmatches digit character. /\d/. equals to /[0-9]/.- 2apples
- 3 Pears
- Apple
- Pear
\Dmatch non digit character. /\D/. equals to /[^0-9]/.- Apple
- Pear
- 2apples
- 3 Pears
\smatches white space. /\s/.- 2 Apples
- Apple or orange
- AppleOrOrange
- PearAndPeach
\Smatches a single character other than white space. /\S/.

\wmatches any alphanumeric words including _. /\w/equals to /[A-Za-z0-9_]/.- &^%$A
match A

\WMatches any non-word character. /\W/. equals to /[^A-Za-z0-9_]/.- Appl#
matches #

Note: the list is not complete. Check Resource links for complete list


Regular Expression properties:

Property Name Description
lastIndexThe index at which to start the next match
ignoreCaseIndicates if the "i" flag was used to ignore case. Returns true or false
globalIndicates if the "g" flag was used for global match. Returns true or false
multilineIndicates if the "m" flag was used match from multiple lines. Returns true or false
sourceReturns the pattern used in regular expression
splitThis method is in String. If match found, returns array of substrings.


Methods related to regular expression:
Method Name Description
execthat executes a search for a match in a string. It returns an array
re.exec(str) - matches the regular expression (re) against the input parameter string (str).

Properties:
[0] - The full string of characters matched

[1], ...[n ] - matched substrings
index - zero based, index of matched string
input - the string match happening against
testtests for a match in a string and returns true or false
re.test(str) - regular expression (re), input parameter string (str). 

matchThis method is in String. Executes a search and returns an array of information or null on a mismatch
str.match(re) - regular expression (re) pattern to match on string (str).



searchThis method is in String. Returns the index if match found, else -1.
str.search(re) - regular expression (re) pattern to search from string (str).

replaceThis method is in String. Replaces matched substring with replacement substring.
str.replace(re, newSubStr) - replace substring from string (str) if match found based on regular expression (re) pattern with new sub string (newSubStr).

Note: a function can be used instead of newSubStr as replacement

splitThis method is in String. If match found, returns array of substrings.
str.split([separator[, limit]]) - Splits the string (str) based on separator. Limit value can be specified which is optional. If used, it splits on every match on separator but truncates the array to meet the limit.


Regular expression with flags:

Syntax: /regular expression/flag;
Flags:

i - case ignore search

g - global search

m - multi line search


Examples
:


1. Replace all instances of e or E in a String - /e|E/g.

2. 




Resources:
1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
2. 

Friday, September 18, 2015

Hand out - Javascript - requireJS - part-01

What is RequireJS?
RequireJS is a module loader for JavaScript which facilitate module based programming where large application is broken down into relatively small and manageable code blocks. That leads to the problem of managing those dependencies between modules and emerges the need of module loader. RequireJS is one of the most popular. It improves script load speed.


Few concepts:

1. Without RequireJS, html file has to have all the dependent scripts loaded using script tag and the correct order has to be maintained. That is treated as synchronous loading and scripts will be loaded one at a time which slows the page view. RequireJS uses AMD (Asynchronous Module Definition) where modules are loaded in parallel and boosts the page load


2. Using require() vs. define()
Both require() and define() to load dependencies. The require() function is used to run immediate functionalities, while define() is used to define modules for use in multiple locations. In the example, in both app.js and main.js, need to run immediately. So, require() was used. Check the code below to get better understanding. 

3. In the example, in all places where require() is used, can be replaced with requirejs or vice versa.

4. In main.js, define() could be used instead of require().


Use RequireJS - integrate jQuery/bootstrap and print hello world in console


1. Folder structure - this folder structure is not that important to test RequireJS as long as references are pointed correctly. But have good folder structure helps organizing the files, improves manageability. Folder structure followed -




css - for css files
fonts - for fonts
img - for images 
js - any JavaScript 
js/app - will have application specific js files
js/vendors - any third party js (like - jQuery, bootstrap etc.)
app.js - contains RequireJS configuration
main.js - contains the web app dependencies and once loaded can start application using any framework
index.html - to load the script

note: app.js and main.js can be combined into one and point from script in html file

2. Download RequireJS and put in js/vendors folder

3. Define RequireJS script in the html


Explanation:
- only one script tag where src refers to RequireJS. data-main attribute tells require.js to load js/app.js after require.js loads. js extension is not needed as RequireJS works only on JavaScript

4. Configure RequireJS to load dependecies (jQuery/bootstrap)


Explanation:

baseUrl - the root path to use for all module lookups
paths - path mappings for module names not found directly under baseUrl. The path settings are assumed to be relative to baseUrl, unless the paths setting starts with a "/" or has a URL protocol in it ("like http:")
shim - Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies

End of the file, it makes call to main.js using require() function

5.  Load application dependencies

















Explanation: 
- application code requires jQuery. 
- require method - takes two parameters. First parameter takes dependency array. Second parameter defines the function which have application code. In this case just printing a message to screen.

6. Open the index.html file in the browser. Used chrome to view it and developer tool to check console message



Resources:
1. http://requirejs.org/
2. http://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/

Wednesday, September 16, 2015

Hand out - JavaScript - using Jasmine

jasmine what:
Testing framework for javascript code. Very lightweight framework as it is not dependent on any other frameworks or any DOM. This follows BDD (business Driven Development), meaning based on user needs rather than code needs.

Jasmine concepts:


Suite – 
A test suite begins with a call to the global Jasmine function describe with two parameters: a string and a function. String is the title of the suite. Function is the block of code executes the suite.

points - 
  • defined using describe jasmine function
  • describe is a namescope
  • describe can have multiple describe in it

Specs
Defined using describe jasmine function are defined by calling the global Jasmine function it, which, like describe takes a string and a function. The string is the title of the spec and the function is the spec, or test.

Points - 
  • it represents actual unit test
  • it is also a namescope
  • it can have multiple expectations (expect)
  • A spec javascript which points to the module to be tested. Naming convention of spec file is ‘Spec.js’
Expectation
Expectations are built with the function expect which takes a value, called the actual. It is chained with a Matcher function, which takes the expected value.

Points - 
  • expect – to check ‘it’ test passed or not
  • systax – expect().toBe();    

Matcher

Each matcher implements a boolean comparison between actual value and expected value. It reports to jasmine if expectation is true or false. Jasmine will pass or fail the spec.


How to install/use jasmine:

Download link: https://github.com/jasmine/jasmine/releases
Version tested: 2.3.4

Option-01: using jasmine runner in web

Sample application - this application will test a very simple javascript function which simply adds two variables. testJasmine01.html is considered as jasmine spec runner where test result would be shown.

folder structure followed:
















Add jasmine libraries, code to test and jasmine spec definition on code in html:




















Code to be tested: main.js file with a very simple function

var sum = function(a, b){
return a * b;
}


Spec code: mainSpec.js

(function(){
describe("main file", function(){
describe("add method", function(){
it("Should add 2 numbers together", function(){
expect(sum(2,3)).toBe(5);
});
});
});
})();


Run the test: just open the html page in a browser. Output should look like below where the test failed.




















Fix the error: change main.js, * to +


var sum = function(a, b){
return a + b;
}

Run the test again: this time it passes











Modify the spec to add concatenation test:
(function(){
describe("main file", function(){
describe("add method", function(){
it("Should add 2 numbers together", function(){
expect(sum(2,3)).toBe(5);
});

it("Should concatenate two values", function(){
expect(sum('Riaz ', 'Ahmed')).toBe('Riaz Ahmed');
});
});
});

})();

Run the test:















Option-02: using command line jasmine.

This will be covered in a separate post in future.



Resource:

  1. http://jasmine.github.io/2.0/introduction.html

Saturday, September 12, 2015

Hand out - Javascript - quick facts and best practices

Introduction:
This post is to provide some quick refreshing facts and best practices for those folks who haven't worked on JavaScript for a while. For beginners, it's better to go through the basic/advance tutorials first and check back with this.

Some quick facts
  • External JavaScript Advantages
    • Separation of concerns HTML and code
    • HTML and JavaScript can be maintained and read easily
    • Cached JavaScript files can speed up page loads
  • JavaScript Display Possibilities
    • Writing into an alert box, using window.alert()
    • Writing into the HTML output using document.write()
    • Writing into an HTML element, using innerHTML
    • Writing into the browser console, using console.log()
  • JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.
  • All JavaScript identifiers are case sensitive

  • JavaScript ignores multiple spaces. Add white space to script to make it more readable

  • A variable declared without a value will have the value undefined. If re-declare a JavaScript variable, it will not lose its value

  • JavaScript Objects - JavaScript objects are written with curly braces. Object properties are written as name:value pairs, separated by commas
    •  Example: var employee = {name:”Riaz”, address:”Ashland”};
    •  Accessing object properties:
      • objectName.propertyName
      • objectName[propertyName]
    • Accessing object method:
      • objectName.methodName();
      • calling objectName.methodName without () will return function definition
    •  Using an Object Constructor - Sometimes we like to have an "object type" that can be used to create many objects of one type.
      • Example: 
      • function person(first, address) {this.firstName = first;this.address = address;}
        var p1 = new person("Riaz", “Ashland”);
        var p2 = new person("Rahat", “Dhaka”);
    • Object prototype - All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.
    • Adding Properties and Methods to Objects –
      • Add new properties (or methods) to an existing object
        • Example: p1.age = 20; This will add age property to p1 object (above example) but p2 will not have it.
      • Add new properties (or methods) to all existing objects of a given type. This can be done by adding property or method directly in the constructor function.  
      • Add new properties (or methods) to an object prototype - using prototype keyword on an object.
        • Example: p1.prototype.age = 20; This code will add age property to both p1 and p2 objects, though p1.age will have valid value only.
    • JavaScript Objects are Mutable, addressed by reference, not by value. var x = y; The object x is not a copy of y. It is y. Both x and y points to the same object. Any changes to y will also change x, because x and y are the same object
    • In JavaScript, all objects have the valueOf() and toString() methods
    • JavaScript for/in statement loops through the properties of an object
  • typeof operator to find the type of a JavaScript variable
    • typeof "Riaz"                // Returns string
    • typeof 10                      // Returns number
    • typeof false                  // Returns boolean
    • typeof [1,2,3,4]           // Returns object
    • typeof {name:”Riaz”, address:”Ashland”} // Returns object
  • undefined - a variable without a value, has the value undefined. The typeof is also undefined.

  • Null - is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object.
    • Difference Between Undefined and Null
      • typeof undefined             // undefined
      • typeof null                          // object
      • null === undefined          // false
      • null == undefined            // true

  • JavaScript Function
    • Function Invocation - the code inside the function will execute when "something" invokes (calls) the function using operator ():
      • When an event occurs (when a user clicks a button)
      • When it is invoked (called) from JavaScript code
      • Automatically (self invoked)

  • Javascript event
    • list of some common HTML event
      • onchange - An HTML element has been changed
      • onclick - The user clicks an HTML element
      • onmouseover - The user moves the mouse over an HTML element
      • onmouseout - The user moves the mouse away from an HTML element
      • onkeydown - The user pushes a keyboard key
      • onload - The browser has finished loading the page
      • etc...

  • Javascript Array
    • Create array
      • var arrayName = [“item1”, “item2”, ….];
      • var arrayName = new Array(“item1”, “item2”, ….);
    • Array can Have Different Objects in it
    • Array Methods
      • Join() – joins all array elements into a string
      • Push() – add element at the end
      • Pop() – removes last element
      • sort() –
      • reverse() –
      • concat() - creates a new array by concatenating two arrays
      • etc..

  • Javascript regular expression - (more on regular expression)
    • A regular expression is a sequence of characters that forms a search pattern.
    • Syntax
      • /pattern/modifier
    • Methods
      • search() - uses an expression to search for a match, and returns the position of the match.
      • replace() - returns a modified string where the pattern is replaced.
      • test() - searches a string for a pattern, and returns true or false, depending on the result
    • Modifier
      • i - Perform case-insensitive matching
      • g - Perform a global match (find all matches rather than stopping after the first match)
      • m - Perform multiline matching
    • Patterns
      • Brackets are used to find a range of characters
        • example: [abc] [0-9]
      • Metacharacters are characters with a special meaning
        • \d - find a digit
        • \s - find a whitespace character
        • \b - find a match at the beginning or at the end of a word
        • etc...
      • Quantifiers define quantities:
        • n+ - Matches any string that contains at least one n
        • n* - Matches any string that contains zero or more occurrences of n
        • n? - Matches any string that contains zero or one occurrences of n


Best practices:
  • Using document.write() after an HTML document is fully loaded, will delete all existing HTML
  • It is a good idea to place scripts at the bottom of the body element. This can improve page load, because HTML display is not blocked by scripts loading.
  • Avoid String, Number, and Boolean objects. They complicate code and slow down execution speed.
  • If a value assigned to a variable that has not been declared, it will automatically become a GLOBAL variable.
  • Avoid Global Variables - Global variables and functions can be overwritten by other scripts.
  • Always Declare Local Variables - Local variables must be declared with the var keyword, otherwise they will become global variables.
  • It is a good coding practice to initialize variables when you declare them
  • Use === Comparison - the == comparison operator always converts (to matching types) before comparison. The === operator forces comparison of values and type.
  • JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type. Numbers can accidentally be converted to strings or NaN.
  • Don't Use new Object()
    • Use {} instead of new Object()
    • Use "" instead of new String()
    • Use 0 instead of new Number()
    • Use false instead of new Boolean()
    • Use [] instead of new Array()
    • Use /()/ instead of new RegExp()
    • Use function (){} instead of new function()
  • If a function is called with a missing argument, the value of the missing argument is set to undefined. Undefined values can break code. It is a good habit to assign default values to arguments.
  • With JavaScript, null is for objects, undefined is for variables, properties, and methods. To be null, an object has to be defined, otherwise it will be undefined
  •  Only modify own prototypes. Never modify the prototypes of standard JavaScript objects
  • Reduce DOM Access - Accessing the HTML DOM is very slow, compared to other JavaScript statements. If a DOM element needs to access several times, access it once, and use it as a local variable
  • Global variables (or functions) can overwrite window variables (or functions). Any function, including the window object, can overwrite global variables and functions.

Resources:
  1. http://www.w3schools.com/js
  2. http://peerprogrammer.blogspot.com/2015/09/hand-out-javascript-regular-expression.html