javascript Closure IIFE Immediately Invoked Function

Javascript Closure

This is an example of how to use iffe closure example to avoid collisions with other global variables in your programs. By placing the variable in the function it makes it private and not accessible everywhere else that would create a problem.

// global variable bad because of collisions
// break other programs avoid globals
var names = ['zero', 'one', 'two', 'three', 'four', 'five'];

var digit_name = function (n) {
	return names[n];
}

console.log(digit_name(3)) // 'three'

// SLOW - because we have to create an variable array every time you try invoking it.
// prevents collision of global variables - names
var digit_name = function (n) {
	var names = ['zero', 'one', 'two', 'three', 'four', 'five'];
	return names[n];
}

console.log(digit_name(3)) // 'three'

// closure iife - immediate invoked function 
// it executes the function has access to the variable names in the iffy
var digit_name = (function () {
	var names = ['zero', 'one', 'two', 'three', 'four', 'five'];
	return function (n) {
		return names[n];
	}
})();

console.log(digit_name(3)) // 'three'

 

The third way to do this is the best. To avoid collisions.

Power Constructors

  1. Make an object
    • Object Lateral
    • new
    • Object.create
    • call another power constructor
  2. Define some some variables and functions
    • These become private members
  3. Augment the object with privileged methods.
  4. Return the object
function myPowerConstructor(x) {
	var that = otherMaker(x);
	var secret = f(x);
	that.priv = function () {
		//secret x that
	};
	return that;
}

 

Functional Inheritance

function gizmo(id) {
	return {
		id: id,
		toString: function () {
			return "gizmo " + this.id;
		}
	};
}

function hoozit(id) {
	var that = gizmo(id);
	that.test = function (testid) {
		return testid === this.id;
	};
	return that;
}

Source:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression

Javascript – How to Create Functions to replace text, factorial, check if it’s even

These are some code snippets on how to create functions to check if a number is even. Do a factorial with a for loop. Do a text replacement with regular expressions.

// isEven f(x)
function isEven(arg) {
	return arg%2 === 0
}
// factorial f(x)
function factorial(num) {
	var result = 1;
	for(var i = 2; i <= num; i++) {
		result = result * i;
	}
	return result;
}
// kebabToSnake() Replace a string "-" with '_'s
function kebabToSnake(str) {
	var newStr = str.replace(/-/g , "_");
	return newStr;
}

How to Setup Babel es2015 Javascript on Windows 8.1?

First create a folder:
Then CD into that folder through CMD
Then do the follow in command-line

npm init
npm install -g babel-cli
npm install babel-preset-es2015–save-dev

Then create app.js.es6 file

Then use this example code:

class Person {
	constructor(name) {
		this.name = name;
	}
	greet(){
		return "Hello I am ${this.name}";
	}
}

let person = new Person("Tyler");
console.log(person.greet());

babel app.js.es6 –presets2015 | clip

Clip copies the string from commandline. Then you should get the follow code output:

"use strict";

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Person = (function () {
	function Person(name) {
		_classCallCheck(this, Person);

		this.name = name;
	}

	_createClass(Person, [{
		key: "greet",
		value: function greet() {
			return "Hello I am ${this.name}";
		}
	}]);

	return Person;
})();

var person = new Person("Tyler");
console.log(person.greet());

Now we want to create an index.html file

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title></title>
</head>
<body>
	<h2>ES2015</h2>

	<script src="app.js"></script>
</body>
</html>

babel app.js.es6 –presets es2015 > 5

Now we are going to create a file called .bablrc this file will shorten the command to compile the babel file

{
	presets: ["es2015"]
}

Next we type in this code to make compiling es2015 javascript faster.

babel app.js.es6 > app.js

babel_CMD_setup

https://github.com/JasonDeving/babel2015windowssetup

Reserved Characters in URLs – PHP

These are list of following of reserved characters for links:

! # $ % & ( ) * + , / : ; = ? @ [ ]

These characters need to be encoded so it doesn’t interfere with the function of the URL.

These characters will turn into %21 hexadecimal characters.

A fix for this is

<?php
	urlencode($string);

?>

 

URLencode

  • Letters, numbers, underscores, and dash are unchanged
  • Reserved characters become % + 2 digit hexadecimal
  • Spaces become “+”
  • Use this for query string after that ?

rawurlencode

  • rawurlencode should only be used for file path
  • path is the part before “?”
  • spaces must be %20
  • it’s newer

Javascript – Magic 8 Ball Script

This is a magic 8 ball program written in html and javascript. So it’s very lean fast and quick. You are free to use this script because it’s open source I made this solely for fun. So fork it. This is basically a random answer generator which uses random number and switch statement to be written. Have fun. 😉

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Magic 8 ball</title>
</head>
<body>
	<input type="text" placeholder="Ask your question?">
	<button onclick="myFunction()">Answer</button>
	<p id="demo"></p>

	<script>
function myFunction() {
	function getRandomArbitrary(min, max) {
	return Math.floor(Math.random() * (max - min) + min);
	}
	var num = getRandomArbitrary(1,6);

	switch(num) {
	    case 1:
	        answer = "Yes";
	        break;
	    case 2:
	        answer = "No";
	        break;
	    case 3:
	        answer = "Try Again";
	        break;
	    case 4:
	        answer = "Outlook not so good";
	        break;
	    case 5:
	        answer = "Most definitely!";
	        break;
	}
	document.getElementById("demo").innerHTML = answer;
}
	</script>
</body>
</html>

 

Magic 8 Ball Demo

Why Sass is Awesome?

Why is sass awesome?

It makes css work way easier and faster. You have to have ruby on rails installed and the sass gem installed.

First install sass with this command (you only need to do it once)
gem install sass

Type in CLI first navigate to correct director with cd

sass – watch .

to compile .scss into .css

Below is to install the bourbon library for css
gem install bourbon

bourbon library

scss advanced code

@mixin box($size, $color, $display: block) {
	width: $size;
	height: $size;
	background: $color;
	display: $display;
}

a {
	@include box($size: 10px, $color: blue);
}

// for the list don't forget ... example below members... for a list /w out is static
@mixin band($name, $members...) {
	@each $member in $members {
		.#{$name}.#{$member} {
			background: url("images/#{$name}/#{$member}.jpg");
		}
	}
}

div {

	margin: 0px 0 0 10px;
}

@include band(radiohead,thom, jonny, colin, phil);
@include band(nin, cuties);

It compiles into .css:

a {
  width: 10px;
  height: 10px;
  background: blue;
  display: block; }

div {
  margin: 0px 0 0 10px; }

.radiohead.thom {
  background: url("images/radiohead/thom.jpg"); }

.radiohead.jonny {
  background: url("images/radiohead/jonny.jpg"); }

.radiohead.colin {
  background: url("images/radiohead/colin.jpg"); }

.radiohead.phil {
  background: url("images/radiohead/phil.jpg"); }

.nin.cuties {
  background: url("images/nin/cuties.jpg"); }

Hello World in React Js

This is hello word app created with react.js This is my first simple script. Yes, I know it’s easier to do this in html. But I wanted to do this in JSX to make thing more complicated.

 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Jsx</title>
</head>
<body>
	
	<! – container node – >
	<div id="jsx">
		
	</div>
	<! – container node – >
	<div id="dom">
		
	</div>
	<script src="https://fb.me/react-0.11.1.js"></script>
	<script src="https://fb.me/JSXTransformer-0.11.1.js"></script>
	<script type="text/jsx">
	/** @jsx React.DOM */

	var MessageBox = React.createClass({

		render: function(){
			return (
				<div className="container">
				<h1>Hi</h1>
				<SubMessage />
				</div>

				);
		}
	});

	var SubMessage = React.createClass({
		render: function(){
			return (
			<small>Sub message</small>
			);
		}
	});

	var reactComponentJSX = React.renderComponent(
		<MessageBox />,
		document.getElementById('jsx')
		);
	</script>
</body>
</html>

Building a Calculator With Angular Js

index.html

Angular js Simple Calculator Example Code

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example68-production</title>
  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
  

  
</head>
<body ng-app="">
  First Num<input type="number" ng-model="number1">
Second Num<input type="number" ng-model="number2">
  <button ng-click="count = count + number1" ng-init="count=0">
  Add
</button>
<button ng-click="count = count - number2" ng-init="count=0">
  Subtract
</button>
<button ng-click="count = count * number2" ng-init="count=0">
  multiply
</button>
<button ng-click="count = count / number2" ng-init="count=0">
  divide
</button>
<button ng-click="count = 0" ng-init="count=0">
  clear
</button>
<span>
  count: {{count}}
</span>
</body>
</html>

app.js

it('should check ng-click', function() {
  expect(element(by.binding('count')).getText()).toMatch('0');
  element(by.css('button')).click();
  expect(element(by.binding('count')).getText()).toMatch('1');
});

Gulp To Create One Javascript File to Speed Up Your Production Server

First install node.js
Type this in commandline

npm install gulp
npm install gulp-concat –save-dev
npm install gulp-uglify –save-dev
npm install gulp-rename –save-dev

'use strick';

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename');

gulp.task("concatScripts", function(){
	//combine all these scripts
	gulp.src([
		'js/jquery.js', 
		'js/sticky/jquery.stick.js', 
		'js/main.js'])
	//create file
	.pipe(concat("app.js"))
	// put in folder destination
	.pipe(gulp.dest("js"));

});

gulp.task("minify", function(){
	gulp.src("js/app.js")
		.pipe(uglify())
		.pipe(rename("app.min.js"))
		.pipe(gulp.dest("js"));

});

gulp.task("default", ["hello"], function(){
	console.log("this is the default task");
});

Then type in gulp “task or functions”

https://github.com/osscafe/gulp-cheatsheet

Sticky Navigation Bar Souce Code

Demo

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Stick Nav</title>
	<style>
body {
	margin: 0 0 0 0 !important;
	padding: 0; 
}
.header {
	padding: 20px 0;
	background-color: #333;
}
.nav {
	padding: 5px 0;
	background-color: slategrey;
	position: -webkit-sticky;
	top: 0px;
	z-index: 1;
}
ul {
	list-style: none;
}
li {
	display: inline;
}
.header, .nav {
	text-align: center;
	color: #fff;

}
.content {
	width: 600px;
	margin: 10px auto 100px;
}
.sticky {
	position: fixed;
	width: 100%;
	left: 0;
	top: 0;
	z-index: 100;
	border-top: 0;
}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
	<script>
	$(document).ready(function() {
var stickyNavTop = $('.nav').offset().top;
 
var stickyNav = function(){
var scrollTop = $(window).scrollTop();
      
if (scrollTop > stickyNavTop) { 
    $('.nav').addClass('sticky');
} else {
    $('.nav').removeClass('sticky'); 
}
};
 
stickyNav();
 
$(window).scroll(function() {
    stickyNav();
});
});
</script>
</head>
<body>
<div class="wrapper">
	<div class="header">
		Header
	</div>
	<div class="nav">
		<ul>
			<li><a href="#">Home</a></li>
			<li><a href="#">Contact</a></li>
			<li><a href="#">About Me</a></li>
		</ul>
	</div>
	<div class="content">
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad, facilis. Ut vero ab molestias totam, excepturi, at repellendus doloribus, nam vitae non optio obcaecati sequi ipsum, eaque impedit magnam. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis laboriosam error voluptas laudantium repellendus earum blanditiis, tempora delectus dignissimos deleniti, ratione quas doloribus quia. Vel tempore iure est, eligendi sed.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut optio rem, accusantium expedita dignissimos eligendi quidem vero facilis consequatur eos similique, culpa laudantium voluptatum. Ex tempore soluta adipisci veritatis animi!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate eum beatae, omnis maiores consequatur similique impedit porro aliquam cupiditate, tenetur, at dolore in ex doloribus. Omnis iure aut rem vitae.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad, facilis. Ut vero ab molestias totam, excepturi, at repellendus doloribus, nam vitae non optio obcaecati sequi ipsum, eaque impedit magnam. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis laboriosam error voluptas laudantium repellendus earum blanditiis, tempora delectus dignissimos deleniti, ratione quas doloribus quia. Vel tempore iure est, eligendi sed.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut optio rem, accusantium expedita dignissimos eligendi quidem vero facilis consequatur eos similique, culpa laudantium voluptatum. Ex tempore soluta adipisci veritatis animi!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate eum beatae, omnis maiores consequatur similique impedit porro aliquam cupiditate, tenetur, at dolore in ex doloribus. Omnis iure aut rem vitae.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad, facilis. Ut vero ab molestias totam, excepturi, at repellendus doloribus, nam vitae non optio obcaecati sequi ipsum, eaque impedit magnam. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis laboriosam error voluptas laudantium repellendus earum blanditiis, tempora delectus dignissimos deleniti, ratione quas doloribus quia. Vel tempore iure est, eligendi sed.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut optio rem, accusantium expedita dignissimos eligendi quidem vero facilis consequatur eos similique, culpa laudantium voluptatum. Ex tempore soluta adipisci veritatis animi!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate eum beatae, omnis maiores consequatur similique impedit porro aliquam cupiditate, tenetur, at dolore in ex doloribus. Omnis iure aut rem vitae.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad, facilis. Ut vero ab molestias totam, excepturi, at repellendus doloribus, nam vitae non optio obcaecati sequi ipsum, eaque impedit magnam. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis laboriosam error voluptas laudantium repellendus earum blanditiis, tempora delectus dignissimos deleniti, ratione quas doloribus quia. Vel tempore iure est, eligendi sed.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut optio rem, accusantium expedita dignissimos eligendi quidem vero facilis consequatur eos similique, culpa laudantium voluptatum. Ex tempore soluta adipisci veritatis animi!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate eum beatae, omnis maiores consequatur similique impedit porro aliquam cupiditate, tenetur, at dolore in ex doloribus. Omnis iure aut rem vitae.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad, facilis. Ut vero ab molestias totam, excepturi, at repellendus doloribus, nam vitae non optio obcaecati sequi ipsum, eaque impedit magnam. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis laboriosam error voluptas laudantium repellendus earum blanditiis, tempora delectus dignissimos deleniti, ratione quas doloribus quia. Vel tempore iure est, eligendi sed.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut optio rem, accusantium expedita dignissimos eligendi quidem vero facilis consequatur eos similique, culpa laudantium voluptatum. Ex tempore soluta adipisci veritatis animi!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate eum beatae, omnis maiores consequatur similique impedit porro aliquam cupiditate, tenetur, at dolore in ex doloribus. Omnis iure aut rem vitae.</p>
	</div>
</div>

</body>
</html>