Simple javascript function to sort an int array by ASC.

Simple function to sort an array of ints by ASC order, there are built in methods to sort an array, this is just for fun.


function sort(array) {
    var len = array.length;
    var new_ = array;</div>
   for(var x = 0; x < len; x++) {
        for(var i = 0; i < len; i++) {
           if(array[x] < new_[i]) {
                var tmp = new_[i];
                new_[i] = array[x];
                array[x] = tmp;
            }
        }
    }
}

This is the built in function:


var myArray=[8,10,50,5,7,83,24,19,168];

myarray.sort(function(a, b) {
    if(a > b) {
        return 1;
    } else {
       return -1;
    }
});

 

now with a proper way:


myArray.sort(function(a, b) { return a > b ? 1: -1; });

And even better with arrow (ES6):


myArray.sort((a, b) => a > b ? 1 : -1);

Advertisements

JavaScript and ExtJs function to mask a numberfield.

This simple function adds a well format to a field in extjs, use it in a render on a column grid.


function format(value) {
var decimalplaces = 3; // or any other number
var pad = '0';
if(decimalplaces > 0) {
pad += '.';
for(var i = 0; i < decimalplaces; i++) {
pad += '0';
}
}
return Ext.util.Format.number(value, pad);
}

How to copy records from a store and send them by Ajax.

There are many ways of doing this, here is one in ExtJs by Sencha.


function copyStoreData(store) {
var data = store.getRange();
var len = data.length;
var newData = [];

for(i = 0; i < len; i++) {
newData.push(data[i].data);
}

return newData;
}

if you need to appy a filter just do like this, or even in json.


function copyStoreData(store, filter) {
var data = store.getRange();
var len = data.length;
var newData = [];

for(i = 0; i < len; i++) {
if(data[i].get('field') !== filter) {
newData.push(data[i].data);
}
}

return Ext.encode(newData);
}

New getters and setters in Es6 JavaScript.

This is a simple example on how to implemet getters and setters in Es6 JavaScript.


class Point {
constructor(x, y) {
this._x = x;
this._y = y;
}
get X() {
return this._x;
}
get Y() {
return this._y;
}
set X(x) {
this._x = x;
}
set Y(y) {
this._y = y;
}
}

var p = new Point(10, 20);

p.X;

And now how to do it without class system.


function Point(x, y) {
this._x = x;
this._y = y;

this.getX = function() {
return this._x;
};

this.getY = function() {
return this._y;
};

this.setX = function(x) {
this._x = x;
};

this.setY = function(y) {
this._y = y;
};
}

var p = new Point(10, 20);

p.getX();