Some awesome snippets from angular-js source code.

I have started going through the angular-js source code trying to understand the internal workings of the same.
Its about 22000 lines of pure magic and an awesome learning experience for new and experienced developers.
Here are some of the gists that I have collected.
BTW, heres the source code : https://ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular.js
Please feel free to send me any pull requests if you find that the gist could be improved and comment if you have more awesome gists to share !

  1. Cloning an object with multiple nested functions or keys using javascript

  2. Simple function to remove special characters from a string.

  3. Angular: UID function creator

  4. Angular: Simple functions

  5. Simple function to remove special characters from a string.

  6. Angular: Function to calculate the length of string

  7. Angular: Regex to search for html tags

  8. Angular : The actual code behind the magical angular injector dependencies.

Also check out angular-js.in >> A curated list of angular directives.

front-end-developer-tools

Front-end Developer Tools

Nowadays front-end development isn’t just about JavaScript ,html and css there are a lot of other new entrants that will help you to automate your process and save precious development time.
The first technology that you will encounter is grunt.

GRUNT

Grunt is JavaScript task-runner designed to automate almost everything.Its thousand of plugins has you covered for normal tasks like minification , concatenation and linting as well as image compression , building sass , coffeescript or your favorite pre-processor , unit testing , end-to-end testing etc.

It works by defining your development requirements in package.json.
Example


{
"name": "my-project-name",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.2",
"grunt-contrib-jshint": "~0.6.3",
"grunt-contrib-nodeunit": "~0.2.0",
"grunt-contrib-uglify": "~0.2.2"
}
}

Then you define your Gruntfile.js which will contain the individual tasks as well as group tasks which says which files to minify and where to paste them.

A sample gruntfile


module.exports = function(grunt) {

grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';'
},
dist: {
src: ['src/**/*.js'],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
},
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
// options here to override JSHint defaults
globals: {
jQuery: true,
console: true,
module: true,
document: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint', 'qunit']
}
});

grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');

grunt.registerTask('test', ['jshint', 'qunit']);

grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);

};

After that you just run npm install and you have a simple workflow ready.

Grunt Official

BOWER

Bower is the package manager for the front end web development similar to what npm is to node-js.
You have a bower.json

Example bower.json file


{
"name": "my-project",
"version": "1.0.0",
"main": "path/to/main.css",
"ignore": [
".jshintrc",
"**/*.txt"
],
"dependencies": {
"": "",
"": "",
"": " "
},
"devDependencies": {
"": ""
}
}

Bower Official

CoffeeScript

CoffeeScript is a little language for Ruby affectionados that compiles to javascript.Its for you if you don’t like brackets in your code.

This is how you express a one-line function in javascript :-


var square = function(x) {
return x * x;
};

A better more concise version will be in coffeescript :


square = (x) -> x * x

Similarly for Array comprehensions you have :


cubes = (math.cube num for num in list)

instead of the long way in javascript


cubes = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = list.length; _i < _len; _i++) { num = list[_i]; _results.push(math.cube(num)); } return _results; })();

Coffescript Official

SASS / LESS

Less and Sass are CSS pre-processors, meaning that it extends the CSS language, adding features that allow variables, mixins, functions and many other techniques that allow you to make CSS that is more maintainable, themable and extendable.

Less and Sass can run inside Node, in the browser and inside Rhino. There are also many 3rd party tools that allow you to compile your files and watch for changes.

You should be using css pre-processors for large projects .To explain ,Bootstrap uses a central base.less file which contains all the color names , default table spacing , all you need to do is to change that file and it will be propagated throughout.

Yet the best features are mixins or functions which enable you to use lighten , darken , saturate , math functions finally.

Example , here is the LESS code

@base: #f938ab;

.box-shadow(@style, @c) when (iscolor(@c)) {
-webkit-box-shadow: @style @c;
box-shadow: @style @c;
}
.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
.box-shadow(@style, rgba(0, 0, 0, @alpha));
}
.box {
color: saturate(@base, 5%);
border-color: lighten(@base, 30%);
div { .box-shadow(0 0 5px, 30%) }
}

and this is the compiled css code :

.box {
color: #fe33ac;
border-color: #fdcdea;
}
.box div {
-webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}

LESS Official
SASS Official

YEOMEN

Yeomen should be the default scaffolding tool for your next web project.

How to use in three steps :-

npm install -g yo
npm install -g generator-angular-fullstack
yo angular-fullstack myapp

The above commands will install the angular-full-stack generator :
[Note you will need MongoDB installed for this stack]
Yeomen will also install grunt , bower and other goodies directly into your workflow.

These are the list of all the generators available : http://yeoman.io/community-generators.html

Yeoman Official

Sources for Good Articles.

I love reading.period.Normally I prefer to read on my Kindle for articles or a rusty old novel suits me as well.
I have compiled a list of websites for your daily dose of good well written articles.

1.Readability.

This is my top priority for good source of articles.It lists all top reads that people are sharing on readability.
You can be sure that the articles over here will be awesome to read.

2.longform.org

This features all the long articles or mini stories that will be good to read on a bus ride.
Its should be your top priority if you love mini-thrillers or in-depth reviews and articles.
If you are on a reading spree do check out their best of lists. These are the Absolute nuggets of gold for reading .

3.Medium.com

Medium is the third on my list.You should be on the lookout for small, funny ,hilarious , jaw-breaking , mind-bending (insert adjectives) articles.If you are on the lookout for

Their monthly top 100 list is also great list of small useful articles.

Hint : You can even use this browser extension from amazon for sending articles to your Kindle.A true life-save for those who love to read on Kindles.

What do you think ? Have I missed an important articles aggregation website somewhere ?
Do let me know in the comments below.

Web Design Workshop

I had taken a basic Web Design workshop in my college organized via IEEE Vishwakarma Student Chapter.

The Workshop was divided in two phases;the first phase had html and css while the second taught js and bootstrap.
The objective was that the Student has to be able to make simple and basic websites and know how html,css and js works and have upload his own website on https://neocities.org/browse

Day 1

Day 2

javascript reduce

javascript reduce method

The javascript reduce method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

Directly copied from MDN

reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring.

The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

Summary :-

The reduce method is an acculumator function that provides a simpler way to loop through any javascrpt array from left to right and perform incremental function on all the values.

Some examples to help better understand .reduce

1.Calculate the Sum

var calculateSum = function (a) {
	return a.reduce(function  (i,c) {
		return i+c
	});
}

console.log(calculateSum([1,2,3,4])); // <= 10

2.Calculate the product of all the elements of the array :-

var calculateProduct = function  (a) {
	return a.reduce(function  (i,c) {
		return i*c;
	});
}

console.log(calculateProduct([1,2,3,4])); <= 24

3. Calculate the sum of even elements


/* This can be achieved better by using filter Ex.5 */

[1,2,3,4].reduce(function(a,b,i){
  if(i%2 === 0){ 
   return a+b;
  }else{
   return a;
  }
}); //<= 4


4. Flatten an array

var flattenArray = function  (a) {
	return a.reduce(function  (i,c) {
		return i.concat(c);
	})
}

var b = [[1,2,3],[2,3,4],[4,5,6]];

console.log(flattenArray(b)); //<= [ 1, 2, 3, 2, 3, 4, 4, 5, 6 ]

4. Flatten any array of any level recursively

Here we are passing the second argument as an empty array as that will be the initial value of the accumulator.


var b = [2,[1,2,[3,4]],[2,3,4],[4,5,6]];

var flattenRecursive = function  (arr) {
	return arr.reduce(function  (a,b) {
		if (b instanceof Array) {
			return a.concat(flattenRecursive(b));
		}else{
			return a.concat(b);
		}
	},[]);
}

console.log(flattenRecursive(b)); //<= [ 2, 1, 2, 3, 4, 2, 3, 4, 4, 5, 6 ]

5. Using with filter to solve Ex.2

Using filter with reduce makes looping through any array and performing any function much easy.


var filterEvenSum = function  (arr) {
	return arr.filter(function  (a,i) {
		return !(i%2);
	}).reduce(function  (a,b) {
		return a+b;
	});
}

console.log(filterEvenSum([1,2,3,4])); //<= 4

Main Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

jay-svg

How to do SVG path animations

Introduction:

Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics that has support for interactivity and animation.

With the imminent dominance of html5 , svg poses a unique advantage for creating unique interactive experiences.Unlike images , svg are responsive in themselves , can be animated , given classes and ids , can be dynamically created and edited.

A primer in SVG is explained at Blog post with the demo at SVG demo

Heres a demo of what we have made

Step 1 : Download Inkscape

Inkscape is an open-source vector graphics editor similar to Adobe Illustrator, Corel Draw, Freehand, or Xara X. What sets Inkscape apart is its use of Scalable Vector Graphics (SVG), an open XML-based W3C standard, as the native format.

Download

You will need Inkscape to create complex paths which will be used for the svg path animations.

screenshot of inkscape
inkscape

Step 2 : Draw the SVG

Draw the SVG drawing using tools of Inkscape Draw Lines and Bezier Curves.You can edit the curves to suit your needs.This might take some time to make the curves perfect.
Its important to make sure that there is only 1 path throughout the drawing with only one beginning and one end.

Step 3 : Javascript Code for animation


The code works this way , first we give the strokeDasharray property the maximum length of the the path .We also give this length to property strokeDashOffset
Also the path is given a transition of 3s with easing ease-in-out.
Then the property strokeDashOffset is set to 0 which triggers the easing animation.

function  docready () {
	var path = document.querySelector('svg path');
	var length = path.getTotalLength();

	path.style.transition = path.style.WebkitTransition = 'none';

	path.style.strokeDasharray = length + ' ' + length;
	path.style.strokeDashoffset = length ;

        path.getBoundingClientRect();

	path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset 3s ease-in-out';

	// Below line triggers the Animation

	path.style.strokeDashoffset = '0';
}
window.onload = docready;

Source

Step 4 : html file

Copy the svg code generated to any .html file.
To the bottom before the ending body tag , add the above javascript code.
Save it and open the file in your favourite browser.
You can change the stroke-width:4px; to make the line thicker.

There is also a jQuery plugin for it called Lazy Line Painter for making this svg path animations simpler.

DEMO

The main inspiration for this article : http://jakearchibald.com/2013/animated-line-drawing-svg/

The awesome blog of a Javascript developer.