Some ES6 util arrow functions for strings,

Some ES6 util arrow functions for strings, all tested and working
</div>
<div>
<div>let tolower = (string) => string.toLowerCase();</div>
<div>let toupper = (string) => string.toUpperCase();</div>
<div>let trim$ = (string) => string.trim();</div>
<div>letlen$=(string)=> string.length;</div>
<div>let right$ = (string, num) => string.substring(len$(string)-num, len$(string));</div>
<div>let mid$ = (string, start, num) => string.substring(start, start + num);</div>
<div>let left$ = (string, num) => string.substring(0, num);</div>
</div>
<div>

Old news class in PHP.

This code was used to read data from a newspaper headlines witch is no longer available, the client interface was done in Extjs.


class NewsFeeds{
function stripJson($json){
$strip = json_decode($json, true);
$res_arr = '';
foreach ($strip as $row){
if($row['entries'] != null){
foreach($row['entries'] as $data) {
$arr = array('titulo'=>$row['title'], 'title'=>$data['title'], 'publishedDate'=>$data['publishedDate'],'content'=> $data['content'], 'categories' =>$data['categories'][0]);
$res_arr .= Util::iif($res_arr == '', json_encode($arr, JSON_FORCE_OBJECT),','.json_encode($arr, JSON_FORCE_OBJECT));//concatenar o array numa string
}
}
}
return $res_arr;
}
//function to create the file and write to it
function writeToFile($result, $filename, $extension) {
$myFile = $filename.".".$extension;
if(file_exists($myFile)){
unlink($myFile);
}
$fn = fopen($myFile, 'w') or die('Error opening the file');
fwrite($fn, $result);
fclose($fn);
}

function getContentFeeds($url){
return file_get_contents($url);//function to get the contents of a given url
}
}

$Feeds = new NewsFeeds();

$result = $Feeds->getContentFeeds('http://www.google.com/uds/Gfeeds?callback=google.feeds.Feed.RawCompletion&context=0&num=25&hl=pt_PT&output=json&q=http%3A%2F%2Ffeeds.jn.pt%2FJN-ULTIMAS&key=notsupplied&v=1.0');
$result = str_replace("google.feeds.Feed.RawCompletion('0',", '', $result);
$result = str_replace("/* callback */", '', $result);
$result = str_replace(", 200, null, 200)", '', $result);

if (Util::isJson($result)){
echo $callback.'({"feed":['.$Feeds->stripJson($result).']});';//send the data to extjs
$Feeds->writeToFile($callback.'({"root":['.$Feeds->stripJson($result).']});',"feeds","json"); //write to file
} else {
echo 'The Json not valid. ';
}

Some util functions in PHP.

class Util {

public function isJson($string){
if (!empty($string)){
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
} else {
return false;
}
}

public function iif($condition, $true, $false ) {
return ($condition ? $true : $false);
}

public function date_with_micro($format, $timestamp = null) {

if (is_null($timestamp) || $timestamp === false) {
$timestamp = microtime(true);
}
$timestamp_int = (int)floor($timestamp);
$microseconds = (int)round($timestamp - floor($timestamp) * 10000000.0, 0);
$format_with_micro = str_replace("u", $microseconds, $format);

return date($format_with_micro, $timestamp_int);
}

public function object2array($object) { return @json_decode(@json_encode($object),1); }
}

Node Garden XST Javascript

This is my version of Node Garden in XST Lib in JavaScript.

winScreen(600, 600, false);
setTitle('Node Garden');
setFps(30);

var maxDist = 100;
var nodes = [];
var i = 0;
var h = getScreenWidth();
var w = getScreenHeight();

for(i = 0; i < maxDist+50; i++) {
    nodes.push({
        x: rnd(h),
        y: rnd(w),
        vx: rnd(2)-1,
        vy: rnd(2)-1,
        color: getRandomColor()
    });
}

function main() {
    clear();
    for(var i = 0; i < maxDist+50; i++) {         var node = nodes[i];         node.x += node.vx;         node.y += node.vy;         if (node.x > w) {
            node.x = 0;
        }
        else if (node.x < 0) {             node.x = w;         }         if (node.y > h) {
            node.y = 0;
        }
        else if (node.y < 0) {
            node.y = w;
        }
        fillCircle(node.x, node.y, 2,node.color);
    }

    for (var i = 0; i < nodes.length - 1; i++) {
        var nodeA = nodes[i];
        for(var j = i + 1; j < nodes.length; j++) {
            var nodeB = nodes[j];
            var dist = distance(nodeB.x, nodeB.y, nodeA.x, nodeA.y);
            if (dist < maxDist) {
                line(nodeA.x, nodeA.y, nodeB.x, nodeB.y, (1-dist/maxDist), nodeA.color);
            }
        }
    }
}

See it here

XST framework cool movement effect.

Xst is a simple framework developed by me and is kind of a bunch of objects and functions to simulate a basic language.
This is an example of a cool movement with circles.

winScreen(640, 480, false);
setFps(20);
setBackColor(COLOR.WHITE);

//var declaration
var DPI = PI * 2;
var PHIDELTA = DPI / 15;
var PHISTEP  = DPI / 50;

var current_phi = 0;
var radius = 20;
var small_radius = 3;
var distance = 23;
var w = getScreenWidth();
var h = getScreenHeight();

function main() {
    var x, xBall, yBall, phi, phiIndex;
    current_phi += PHISTEP;
    clear();
    for(x=0; x< w+radius; x+=distance) {
        for(y=0; y < h+radius; y+=distance) {
            circle(x, y, radius, COLOR.BLACK);
            phiIndex = (x + y) % (2 * w) / radius;
            phi = phiIndex * PHIDELTA + current_phi;
            xBall = cos(phi) * radius + x;
            yBall = sin(phi) * radius + y;
            fillCircle(xBall, yBall, small_radius, COLOR.BLACK);
        }
    }
} 

See it in action Here.

Bouncing ball on Canvas javascript.

This is a simple html skeleton to hold the canvas element.

<!DOCTYPE HTML>
<html lang="en">
	<head>
		<title>Moving Ball</title>
		<script type="text/javascript" src="bouncing.js"></script>
	</head>
	<body>
		<canvas id="canvas" width="600" height="400">
			<p>Your browser does not support the canvas element.</p>
		</canvas>
	</body>
</html>

This is the javascript code to move the ball.

var FPS = 30;
var x   = 0;
var y   = 0;
var xDirection = 1;
var yDirection = 1;
var image = new Image();
image.src = 'football.png';
var canvas = null;
var ctx2D  = null;

window.onload = function() {
    canvas = document.getElementById('canvas');
    ctx2D  = canvas.getContext('2d');
    setInterval(draw, 1000/FPS);
}

function draw() {
    ctx2D.clearRect(0, 0, canvas.width, canvas.height);
    ctx2D.drawImage(image, x, y);
    x += 1 * xDirection;
    y += 1 * yDirection;

    if (x >= 450) {
        x = 450;
        xDirection = -1;
    } 
    else if (x <= 0) {
        x = 0;
        xDirection = 1;
    }

    if (y >= 250) {
        y = 250;
        yDirection = -1;
    } 
    else if (y <= 0) {
        y = 0;
        yDirection = 1;
    }

}

Simple JavaScript stack Module pattern.

Well i needed a simple stack to hold some values and i came up with this simple stack but you can use an array, i build this just for fun and to implement the module pattern in JavaScript. Have fun.

var mp = (function stack() {
    var _store = {};
    var index  = 0;
    var _push  = function(val) {
        if(val) {
            index++;
            _store[index]=val;
        }
    };
    var _len = function() {
        return index;
    };
    var _pop = function() {
        if (index >= 0) {
          var v = _store[index];
          delete _store[index];
          index--;
          return  v;
        }
    };
    return {
        len : _len,
        push: _push,
        pop : _pop
    };
}());


mp.push(10);
mp.push(11);
mp.push(12);
mp.push(13);
console.log(mp.len());

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);