reduce(callback, initialValue)
callback(accumulatedValue, currentValue, currentIndex, array)
callback -> function(a, b) {
return function(...args) {
return a(b(...args);
}
}
initialValue -> none so it is set to 'f'
currentValue -. is set to 'g'
First call at index 1
=====================
callback -> called on (f, g)
callback(f, g) returns
function(...args) {
return f(g(...args));
}
Second call at index 2
=======================
callback -> called on (function(...args){return f(g...args))}, h)
callback(function(...args){return f(g...args))}, h) returns
function(...args) {
return
(function(...args){
return f(g(...args))
})(h(...args));
}
This will yield f(g(h(...args)))
Monday, October 2, 2017
Monday, September 25, 2017
Thursday, September 21, 2017
splice
// x/../y=>/y
var a = ["x", "..", "y"]
trimDots(a)
console.log(a);
// x/y/../z/1 => x/z/1
a = ["x", "y", "..", "z", "1"]
trimDots(a)
console.log(a)
// x/./y=> x/y
a = ["x", ".", "y"]
trimDots(a)
console.log(a)
// x/../../y/z=>
function trimDots(ary) {
var i, part;
for (i = 0; i < ary.length; i++) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
// If at the start, or previous value is still ..,
// keep them so that when converted to a path it may
// still work when converted to a path, even though
// as an ID it is less than ideal. In larger point
// releases, may be better to just kick out an error.
if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
continue;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
Output:
[ 'y' ] [ 'x', 'z', '1' ] [ 'x', 'y' ]
Iterate thru an array and call function for each element
function each(ary, func) {
if (ary) {
var i;
for (i = 0; i < ary.length; i += 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
var global = {
x: {
y: {
z: "this is z"
}
}
}
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
console.log(getGlobal("x.y.z"));
Output:
this is z
Thursday, August 24, 2017
Wednesday, July 12, 2017
Object.assign
var emp = {
name: 'Joe'
};
Object.assign(emp, {
dept: 'Dev',
promote: ()=>'Manager'
});
console.log(emp);
console.log(emp.promote());
Output:
{ name: 'Joe', dept: 'Dev', promote: [Function: promote] }
Manager
Copy object properties
function copyAll(source, target) {
for (var prop in source) {
target[prop] = source[prop];
}
}
var emp = {};
var joe = {
name: 'Joe',
age: 36
}
copyAll(joe, emp);
console.log(emp);
var sam = {
name: 'Sam',
age: 28,
desig: 'Dev'
}
var hasOwnProp = Object.prototype.hasOwnProperty;
function hasProp(obj, prop) {
return hasOwnProp.call(obj, prop);
}
function copyNew(source, target) {
for (var prop in source) {
if (!hasProp(target, prop)) {
target[prop] = source[prop];
}
}
}
copyNew(sam, joe);
console.log(joe);
var painter = {
school: 'ArtSchool',
medium: 'watercolour'
}
var jay = Object.create(painter);
jay.name = 'Jay';
jay.genre = 'Realism';
jay.trainer = {
onSkype: true,
inPerson: true,
duration: 0.5
}
function copyDeep(source, target) {
for (var prop in source) {
if (!hasProp(target, prop)) {
if (source[prop] === 'object') {
target[prop] = {};
copyDeep(source[prop], target[prop]);
} else {
target[prop] = source[prop];
}
}
}
}
var alice = Object.create(painter);
alice.name = 'Alice';
copyDeep(jay, alice);
console.log(alice);
Output:
{ name: 'Joe', age: 36 }
{ name: 'Joe', age: 36, desig: 'Dev' }
{ name: 'Alice',
genre: 'Realism',
trainer: { onSkype: true, inPerson: true, duration: 0.5 },
school: 'ArtSchool',
medium: 'watercolour' }
Iterate Object properties
var emp = {
name: 'Joe',
age: 36,
desig: 'Web designer'
}
for (var prop in emp) {
console.log(prop);
}
Output:
name age desig
Tuesday, July 11, 2017
Object.hasOwnProperty
var proto = Object.prototype;
var hasOwnProp = proto.hasOwnProperty;
var dog = {
pet: true
};
var labrador = Object.create(dog);
labrador.watchdog=true;
console.log(hasOwnProp.call(labrador, "watchdog"));
console.log(labrador.hasOwnProperty("watchdog"));
function hasOwn(o, prop) {
return hasOwnProp.call(o, prop);
}
console.log(hasOwn(dog, "pet"));
Output:
true true true
call method
var proto = Object.prototype;
var ostring = proto.toString;
function isFunction(it) {
return ostring.call(it) === '[object Function]';
}
function isArray(it) {
return ostring.call(it) === '[object Array]';
}
var a = new Array();
var f = function(){};
console.log("a isArray? " + isArray(a));
console.log("f isFunction? " + isFunction(f));
Output:
a isArray? true f isFunction? true
Monday, July 10, 2017
Sunday, July 2, 2017
Monday, May 15, 2017
Friday, May 12, 2017
Dual not operator
var obj = "OK"; var match = obj.match(/ERROR/); console.log(match); console.log(!!match);Output:
null false
Typeof
var typeOfArray = {
each: function( obj, callback ) {
var i = 0, length = obj.length;
console.log("obj[" + length + "]=>" + obj);
for ( ; i < length; i++ ) {
console.log(obj[i])
callback.call(this, obj[ i ]);
}
}
}
var class2type = {};
var toString = class2type.toString;
typeOfArray.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function(name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function toType(x) {
if (x == null ) {
return x + "";
}
return toString.call(x);
}
function type(x) {
console.log("typeof " + x + "=" + typeof x);
console.log("Object.toString " + toType(x));
console.log("Object type " + class2type[toType(x)]);
}
var n;
type(n);
var x = null;
type(x);
type(2);
type("2");
type("xyz");
type(true);
type({x: 1});
type(2.2);
type(["x", "y"]);
type(function(){});
type (new Boolean(true));
type(new Array(2,3));
type(new Number(2));
type(new Date());
type(new RegExp("[a-b]"));
type(new String("Hi"));
Output:
obj[10]=>Boolean,Number,String,Function,Array,Date,RegExp,Object,Error,Symbol
typeof:6 Boolean
typeof:6 Number
typeof:6 String
typeof:6 Function
typeof:6 Array
typeof:6 Date
typeof:6 RegExp
typeof:6 Object
typeof:6 Error
typeof:6 Symbol
typeof:24 typeof undefined=undefined
typeof:25 Object.toString undefined
typeof:26 Object type undefined
typeof:24 typeof null=object
typeof:25 Object.toString null
typeof:26 Object type undefined
typeof:24 typeof 2=number
typeof:25 Object.toString [object Number]
typeof:26 Object type number
typeof:24 typeof 2=string
typeof:25 Object.toString [object String]
typeof:26 Object type string
typeof:24 typeof xyz=string
typeof:25 Object.toString [object String]
typeof:26 Object type string
typeof:24 typeof true=boolean
typeof:25 Object.toString [object Boolean]
typeof:26 Object type boolean
typeof:24 typeof [object Object]=object
typeof:25 Object.toString [object Object]
typeof:26 Object type object
typeof:24 typeof 2.2=number
typeof:25 Object.toString [object Number]
typeof:26 Object type number
typeof:24 typeof x,y=object
typeof:25 Object.toString [object Array]
typeof:26 Object type array
typeof:24 typeof function (){}=function
typeof:25 Object.toString [object Function]
typeof:26 Object type function
typeof:24 typeof true=object
typeof:25 Object.toString [object Boolean]
typeof:26 Object type boolean
typeof:24 typeof 2,3=object
typeof:25 Object.toString [object Array]
typeof:26 Object type array
typeof:24 typeof 2=object
typeof:25 Object.toString [object Number]
typeof:26 Object type number
typeof:24 typeof Fri May 12 2017 20:45:31 GMT+0530 (India Standard Time)=object
typeof:25 Object.toString [object Date]
typeof:26 Object type date
typeof:24 typeof /[a-b]/=object
typeof:25 Object.toString [object RegExp]
typeof:26 Object type regexp
typeof:24 typeof Hi=object
typeof:25 Object.toString [object String]
typeof:26 Object type string
typeof:1 undefined
Thursday, May 11, 2017
Data types
function type(x) {
console.log("typeof " + x + "=" + typeof x);
}
var n;
type(n);
var x = null;
type(x);
type(2);
type("2");
type("xyz");
type(true);
type({x: 1});
type(2.2);
type(["x", "y"]);
type(function(){});
type (new Boolean(true));
type(new Array(2,3));
type(new Number(2));
type(new Date());
type(new RegExp("[a-b]"));
type(new String("Hi"));
Output:
typeof undefined=undefined
typeof null=object
typeof 2=number
typeof 2=string
typeof xyz=string
typeof true=boolean
typeof [object Object]=object
typeof 2.2=number
typeof x,y=object
typeof function (){}=function
typeof true=object
typeof 2,3=object
typeof 2=object
typeof Fri May 12 2017 13:56:47 GMT+0530 (India Standard Time)=object
typeof /[a-b]/=object
typeof Hi=object
split
var values = "a b c d".split(" ");
console.log("values: " + values);
var i = 0;
for (i in values) {
console.log("values[" + i + "]: " + values[i]);
}
Output:
values: a,b,c,d values[0]: a values[1]: b values[2]: c values[3]: d
Extend an Object
var o = function() {
}
o.extend = function() {
var args = arguments[0];
if (args != null) {
for (arg in args) {
this[arg] = args[arg];
}
}
}
o.extend({x: "I am x", y: "I am y"});
console.log(o.x);
console.log(o.y);
Output:
I am x I am y
Traverse thru object arguments
var x = function() {
var args = arguments[0];
for (argName in args) {
console.log("argument: " + argName);
console.log("value: " + args[argName]);
}
}
x({y: "This is y",
z: "This is z"});
Output:
argument: y value: This is y argument: z value: This is z
Wednesday, May 10, 2017
regex
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([a-z])/g,
Passing function as argument
( function( global, factory ) {
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
});
Monday, May 8, 2017
Sunday, March 19, 2017
Dynamic function
var dinner = {
menu: {
getMenu: function (type) {
var menu = 'menu: ', list = dinner.menu.items.list, items = dinner.menu.items;
function defaultMenu(type) {
var item = "continental" == type ? "Batter Fish" : "Rice";
console.log("From defaultMenu " + item);
return item;
};
for (var i = 0; i < list.length; i++) {
console.log("Get menu for " + list[i] + "/" + type);
menu += (items[list[i]].getMenu || defaultMenu)(type);
if (i < list.length - 1) {
menu += ",";
}
}
return menu;
},
items: {
list: ['starter', 'maincourse'],
starter: {
getMenu: function (type) {
var item;
if ("continental" == type) {
item = "Baked Mushrooms";
} else if ("chinese") {
item = "Spring Rolls";
} else {
item = "Baked Potatoes";
}
console.log("From starter menu " + item);
return item;
}
},
maincourse: {
getCustomizedMenu: function (ingredients) {
}
}
}
}
}
console.log(dinner.menu.getMenu("continental"));
console.log(dinner.menu.getMenu('chinese'));
Output:
Get menu for starter/continental From starter menu Baked Mushrooms Get menu for maincourse/continental From defaultMenu Batter Fish menu: Baked Mushrooms,Batter Fish Get menu for starter/chinese From starter menu Spring Rolls Get menu for maincourse/chinese From defaultMenu Rice menu: Spring Rolls,Rice
Wednesday, March 15, 2017
Arguments example
The arguments object is a local variable available within all functions.
It contains the arguments passed into the function.
var f = function()
{
var list = arguments;
for (var i = 0; i < arguments.length; i++) {
console.log("argument: " + list[i]);
}
}
f("one");
f("one", "two");
Output:
argument: one argument: one argument: two
Anonymous function
Below is an expression where the anonymous function is evaluated and result is assigned to variable
x.
var x = function() {
console.log("Function ran");
}();
If we don't assign it to a variable, there will be a syntax error.
function() {
console.log("Function ran");
}();
You'd get a syntax error, because the JS parser thinks it is a statement. Below will work:
function f() {
console.log("Function ran");
};
f();
If you notice the above worked as the function has now a name and then we called the function.
But then how do we make the parser know that we want an anonymous function as an expression?
would see the 'function' keyword and assume you're starting a function statement of the form:
If an entire javascript is about execution of a function then the function need to be an anonymous function with parenthesis around it.
(
function() {
console.log("Function ran");
}
)();
Output:
Function ran
Sunday, March 12, 2017
Array push Example
function toArray(source)
{
var result = [];
for (var i = 0; i < source.length; i++)
result.push(source[i]);
return result;
};
console.log(toArray("Hello").toString());
Output:
H,e,l,l,o
Saturday, March 11, 2017
Object Example
Run the below snippet in chrome's developer tools.
function fullName(initial,firstName) {
return initial + "." + firstName;
}
var person = [{
firstName:"Sam",
initial:"M",
age:42,
address:{nbr:10, street:"Street1", place:"Oakland"},
name:fullName(person[0].firstName,person[0].initial)
},
{
firstName:"Shyam",
initial:"N",
age:42,
address:{nbr:10, street:"Street1", place:"Oakland"},
name:function(){return this.initial + "." + this.firstName;}
},
{
"first-name":"Ryan",
initial:"S"
}
];
console.log(person[0].name);
console.log(person[1].name());
console.log(person[1].name);
console.log(person[1].address.place);
console.log(person[2]["first-name"]);
If the object key has a hyphen in it, you won't be able to use it directly but will work if is surrounded with quotes.
As you can see from above object literal person declared has key first-name surrounded with quotes.
In order to refer to the property, you will use:
person[2]["first-name"];Output:
M.Sam
N.Shyam
function (){return this.initial + "." + this.firstName;}
Oakland
Ryan
Array Example
array.html:
<html>
<head>
<script type="text/javascript">
function printPersons() {
var persons = new Array();
persons[0] = ["Sam", 41, [10, "street1", "Oakland"]];
persons[1] = ["Shyam", 21, [1, "street2", "Mumbai"]];
persons[2] = ["Rob", 32, [12, "street3", "Rotterdam"]];
var msg = "";
document.open();
for (var i = 0; i < persons.length; i++) {
msg = msg + persons[i][0] + "-" + persons[i][1] + "-" +
persons[i][2][0] + "-" + persons[i][2][1] + "-" +
persons[i][2][2] + "<br/>";
}
document.write(msg);
document.close();
}
</script>
</head>
<body onload="printPersons()">
Array example
</body>
Output:
Sam-41-10-street1-Oakland Shyam-21-1-street2-Mumbai Rob-32-12-street3-Rotterdam
Friday, March 10, 2017
Subscribe to:
Posts (Atom)


