Get object from array by value without loop in javascript

var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
];
var result = jsObjects.filter(function( obj ) {
return obj.b == 6;
});
result

Advertisements

Enumerable in JavaScript

Object.defineProperty(obj, 'answer', {
  value: 42,
  writable: true,
  enumerable: true,
  configurable: true
});

The property enumerable specifies a specific property of an object to be available for operations.

The default properties of inbuilt objects in JavaScript are not enumerable that means they can not be listed by using for in loop.

When you try to get the properties of an object, the default properties are not being listed because of enumerable false assigned to them. These properties are not listed when you try to get the properties of that object.

var o = {};
var a = [];
o.prop = 'is enumerable';
a[0] = 'is enumerable';

o.propertyIsEnumerable('prop');   // returns true
a.propertyIsEnumerable(0);        // returns true
a.propertyIsEnumerable('length');   // returns false

One can check if the property is enumerable by using propertyIsEnumerable. The length is a default property of an array object. But it is not listed when you try to get the keys/properties in an array.

Array.fill method in JavaScript

We are used to create arrays with loop.

A better way to create a long array with around 10,000,000 entries is to use the fill method which is fast and reliable.

E.g.

Var a = new Array(10000000);
a.fill(“satya”);
console.log(a);

Fill can take two extra parameters as well.

a.fill(“satya”, 0, 100);
this will fill the array starting from 0th index till 100th index.

Phaser bow and arrow game, trajectory

The most popular phaser framework is very helpful to create html5 and javascript games.

I have come up with a simple trajectory code for a bow and arrow game.


var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', {
  preload: preload,
  create: create,
  update: update
});

var bow, bag, arrow, angle;
var score=0;
var x;
var y;
var oldx, oldy;
var xVel;  // calculate this based on distance
var yVel;  // 
var g = 0.25;
var arrowCreated = false;
var shot = false;

function preload() {
  game.load.image('bag', bagURI);
  game.load.image('bow', bowURI);
  game.load.image('arrow', arrowURI);

}

function create() {
  game.world.setBounds(0, 0, 800, 600);
  bow = game.add.sprite(100, 250, 'bow');
  bow.anchor.setTo(0.5);
  
  bag = game.add.sprite(650,300,'bag');
  bag.anchor.setTo(0.5);
  
  
  arrow = game.add.sprite(bow.x, bow.y, 'arrow');
  arrow.anchor.setTo(0.5);
  arrow.scale.setTo(0.5);
  arrow.angle = bow.angle;
  x = oldx = arrow.x;
  y = oldy = arrow.y;
  //game.input.onDown.add(createArrow, this);
  game.input.onUp.add(shootArrow, this);
}

function update() {
  //console.log(shot);
  if (!shot) {
    angle = Math.atan2(game.input.mousePointer.x - bow.x, -(game.input.mousePointer.y - bow.y)) * (180 / Math.PI) - 180;
    bow.angle = arrow.angle = angle;
    
  } else {
    
    //console.log("x",x,"y",y,"xVel",xVel,"yVel",yVel,"oldx",oldx,"oldy",oldy);
    
    x += xVel;
    y += yVel;
    yVel += g;

    arrow.x = x;
    arrow.y = y;
    
    
    arrowAngle = Math.atan2(x-oldx, -(y-oldy)) * (180 / Math.PI);
    arrow.angle = arrowAngle;
    /* need to write new arrow code */
    
     oldx = x;
     oldy = y;
    
    
    if(arrow.y>600) {
      resetArrow();
    }
    
    
    var intersects = Phaser.Rectangle.intersection(arrow, bag);
    if(intersects.width>0) {
      //console.log(intersects.width);
      resetArrow();
      score=score+45;
      console.log(score);
    }
    
  }
}
function resetArrow() {
  shot = false;
  arrow.x=bow.x;
  arrow.y=bow.y;

  x=oldx=arrow.x;
  y=oldy=arrow.y;
}
function createArrow() {
  arrowCreated = true;
}

function shootArrow() {
  if(!shot) {
    shot = true;
    xVel = - (game.input.mousePointer.x-bow.x)/6;
    yVel = - (game.input.mousePointer.y-bow.y)/6;
  }
}

 

How to use Namespace in JavaScript

In JavaScript there is no concept of namespace. But we can create an object and assign the same to window. Then we write all our code inside the object.

That way, the global scope is not polluted.

Normally we use the application name as our namespace object.

There are few different ways to create namespace in JavaScript.

if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}

The above syntax does not take any dependencies. It creates a global object and that object is being used to write code.

(function( skillet, $) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        // can return a private variable value
    };

    //Private Method
    function addItem( item ) {
        // not accessible out side the namespace object
    }
}( window.skillet = window.skillet || {}, jQuery ));

The above syntax has the full feature of a namespace.

var app = new function() {
    var privateFunction = function() {    };
    this.publicFunction = function() {    };
};

The above is with functional programming concept.

var app = app = app || {};
app.Foo = { "alert" : "test"};
app.Bar = function(arg) 
{
    alert(arg);
};
app.Bar("Hey");
with(app) {
   Bar(Foo.alert);
}

The above is empty object creation style and later you assign properties and methods.

The above syntax will give you access to the namespace object from any other file in the application without any issues in all the browsers.

In Modular pattern of development, one can use a global namespace as well as child namespaces like below.

namespace = window.namespace || {};
namespace.module1 = namespace.module1 || {};
namespace.module2 = namespace.module2 || {};

later you assign private and public methods as well as properties to the modules.

 

Singleton Design Pattern in JavaScript

var Singleton = (function () {
var instance;

function createInstance() {
   var object = {"name":"I am the instance"};
   return object;
}

return {
   getInstance: function () {
      if (!instance) {
         instance = createInstance();
      }
      return instance;
   }
};
})();


var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();

alert("Same instance? " + (instance1 === instance2));

In singleton design pattern, we create a single instance of any object. Duplicate instances are being restricted. This is useful to handle objects like timer.

Singleton class is a self executable function assigned to a variable.

It has an instance variable, a create instance method and a getInstance method inside it.

It returns the instance from inside getInstance method. If the instance is already available it returns the same otherwise it calls the createInstance method.

createInstance method returns an object.

To create an instance from the object, user variable name.getInstance() method.

How to add a new function to an existing javascript object

Javascript allows us to extend any exiting objects by using prototype.

String extend

String.prototype.reverse = function() {
return this.split(“”).reverse().join(“”);
}

var s = “satya”;
console.log(s.reverse());

 

Array extend

Array.prototype.first = function() {
return this[0];
}
console.log([1,2,3,4,5].first());

 

Object extend

Object.prototype.keys = function() {
var keys = [];
for(var key in this) {
keys.push(key);
}
return keys;
}

var obj = {“name” : “Satya”, “age” : “34”};

console.log(obj.keys());