Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jonas Raoni Soares Silva http://www.jsfromhell.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 74 total  RSS 

Replace working as PHP str_replace //JavaScript Function

Useless JavaScript implementation of the php function str_replace.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

function replace(f, r, s){
	var ra = r instanceof Array, sa = s instanceof Array, l = (f = [].concat(f)).length, r = [].concat(r), i = (s = [].concat(s)).length;
	while(j = 0, i--)
		while(s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j < l);
	return sa ? s : s[0];
}

Output JavaScript variables from PHP

Class with useful static methods for outputting PHP values into JavaScript format.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

class JS{
	//generic and maybe not the desired results xD
	function value($o){
		if($o === null)
			return 'null';
		$t = strtolower(gettype($o));
		if($t == 'string' && is_numeric($o) && ($o[0] || strlen($o) == 1) || in_array($t, array('double', 'integer')))
			$t = 'number';
		elseif($t == 'string' && preg_match('@^\d{4}(?:-\d{1,2}){1,2}(?: (?:\d{1,2}:){2}\d{1,2})?$@', $o)) //strtotime works also with "strange" values strtotime('x')
			$t = 'date';
		elseif($t == 'array' && ($c = count($k = array_keys($o))) && $k !== range(0, $c - 1))
			$t = 'object';
		elseif(!in_array($t, array('boolean', 'string', 'array', 'object')))
			$t = 'string';
		$t = 'from' . $t;
		return self::$t($o);
	}
	function fromNumber($o){
		return +$o . '';
	}
	function fromObject($o){
		$r = array();
		foreach($o as $n => $v)
			$r[] = self::fromString($n) . ':' . self::value($v);
		return '{' . implode(',', $r) . '}';
	}
	function fromBoolean($o){
		return $o ? 'true' : 'false';
	}
	//$q = should quote? 
	//$c = char that will be used to quote
	function fromString($o, $q = true, $c = '"'){
		return ($p = $q ? $c : '') . preg_replace('/\r\n|\n\r|\r/', '\n', str_replace($c, '\\' . $c, str_replace('\\', '\\\\', $o))) . $p;
	}
	function fromArray($o){
		$s = '';
		foreach($o as $v)
			$s .= ($s ? ',' : '') . self::value($v);
		return '[' . $s . ']';
	}
	function fromDate($o){
		(is_numeric($o) && $o = +$o) || ($o = strtotime($o)) > 0 || ($o = mktime());
		$o = explode(',', date('Y,n,j,G,i,s', $o));
		foreach($o as $i => $v)
			$o[$i] = +$v;
		return 'new Date(' . implode(',', $o)  . ')';
	}
}


Example

$o = new stdClass;
$o->abc = 123;
echo implode("\n<br />", array(
	JS::value('1984-07-22 11:30:12'),
	JS::value('Test'),
	JS::value(1234),
	JS::value(true),
	JS::value(array(1,2,3)),
	JS::value(array('lala' => 'x')),
	JS::value($o)
));

Point Inside a Polygon //JavaScript Function


Checks whether a point is inside a polygon.
Adapted from: [http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html]

[UPDATED CODE AND HELP CAN BE FOUND HERE: Point Inside a Polygon]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/is-point-in-poly [v1.0]

function isPointInPoly(poly, pt){
	for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
		((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
		&& (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
		&& (c = !c);
	return c;
}


Example

<script type="text/javascript">
//<![CDATA[

points = [
	{x: 0, y: 0},
	{x: 0, y: 50},
	{x: 50, y: 10},
	{x: -50, y: -10},
	{x: 0, y: -50},
	{x: 0, y: 0}
];

alert(isPointInPoly(points, {x: 10, y: 10}) ? "In" : "Out");

//]]>
</script>

UTF-8 Converter //JavaScript Object




Converts a sequence of ANSI characters to UTF-8 and vice-versa.

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/geral/utf-8 [v1.0]

UTF8 = {
	encode: function(s){
		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
		);
		return s.join("");
	},
	decode: function(s){
		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
			((a = s[i][c](0)) & 0x80) &&
			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
		);
		return s.join("");
	}
};


Example

var s = "aáéíóúe";
document.write(
	('UTF8.encode("' + s + '") = ').bold(), UTF8.encode(s), "<br />",
	('UTF8.decode(UTF8.encode("' + s + '"))) = ').bold(), UTF8.decode(UTF8.encode(s))
);

TimeLine //JavaScript Class




Simulates the Adobe Flash timeline. You define the amount of frames, the speed in fps (frames per second) and, at each frame passage an event is called, useful for animations.

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/timeline [v1.0]

TimeLine = function(fps, f){
	this.fps = fps, this.frames = f;
};
with({o: TimeLine, $: TimeLine.prototype}){
	o.timers = [];
	$.running = !!($.current = +(o.timer = $.time = null));
	o.run = function(){
		var o = this;
		o.timer || (o.timer = setInterval(function(){
			for(var h, d = +(new Date), t = o.timers, i = t.length; i--;){
				(!t[i].running || ((d - t[i].time) / (1e3 / t[i].fps) > t[i].current + 1 &&
				t[i].onframe(++t[i].current), t[i].current >= t[i].frames)) &&
				(h = t.splice(i, 1)[0], h.stop(1));
			}
		}, 1));
	};
	$.start = function(c){
		var o = this, t = TimeLine;
		if(o.running) return;
		o.running = true, o.current = c || 0;
		o.time = new Date, o.onstart && o.onstart();
		if(!o.onframe || o.frames <= 0 || o.fps <= 0)
			return o.stop(1);
		t.timers.push(this), t.run();
	};
	$.stop = function(){
		var o = this;
		o.running = false;
		if(!TimeLine.timers.length)
			TimeLine.timer = clearInterval(TimeLine.timer), null;
		arguments.length && o.onstop && o.onstop();
	};
}


Example


<div id="box" style="position: absolute; top: 100px; background: #efe; width: 100px; height: 100px">25 fps</div>
<div id="box2" style="position: absolute; top: 300px; background: #ff9; width: 100px; height: 100px">12 fps</div>

<strong>TimeLine working together with the ease in quad function.</strong><br />

<script type="text/javascript">
Math.ease = function (t, b, c, d) {
	if ((t /= d / 2) < 1)
		return c / 2 * t * t + b;
	return -c / 2 * (--t * (t - 2) - 1) + b;
};

var o = new TimeLine(25, 50), d = document, b = d.getElementById("box");
o.onframe = function(){
	b.style.left = Math.ease(this.current, 0, 400, 30) + "px";
};
o.onstart = function(){
	d.body.appendChild(d.createTextNode("Started"));
};
o.onstop = function(){
	d.body.appendChild(d.createTextNode(" - Finished (" + (((new Date) - this.time)) + " msec)"))
	d.body.appendChild(d.createElement("br"));
	this.start();
};
o.start();


var o2 = new TimeLine(12, 50), b2 = d.getElementById("box2");
o2.onframe = function(){
	b2.style.left = Math.ease(this.current, 0, 400, 30) + "px";
};
o2.onstop = function(){
	this.start();
};
o2.start();
</script>

Selection //JavaScript Class




Retrieves and sets the cursor position, as well the selected text of inputs and textareas. After searching, I saw it's the only code which retrieves right information in textareas under Internet Explorer without damaging the "Ctrl+Z"

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/forms/selection [v1.0]

Selection = function(input){
	this.isTA = (this.input = input).nodeName.toLowerCase() == "textarea";
};
with({o: Selection.prototype}){
	o.setCaret = function(start, end){
		var o = this.input;
		if(Selection.isStandard)
			o.setSelectionRange(start, end);
		else if(Selection.isSupported){
			var t = this.input.createTextRange();
			end -= start + o.value.slice(start + 1, end).split("\n").length - 1;
			start -= o.value.slice(0, start).split("\n").length - 1;
			t.move("character", start), t.moveEnd("character", end), t.select();
		}
	};
	o.getCaret = function(){
		var o = this.input, d = document;
		if(Selection.isStandard)
			return {start: o.selectionStart, end: o.selectionEnd};
		else if(Selection.isSupported){
			var s = (this.input.focus(), d.selection.createRange()), r, start, end, value;
			if(s.parentElement() != o)
				return {start: 0, end: 0};
			if(this.isTA ? (r = s.duplicate()).moveToElementText(o) : r = o.createTextRange(), !this.isTA)
				return r.setEndPoint("EndToStart", s), {start: r.text.length, end: r.text.length + s.text.length};
			for(var $ = "[###]"; (value = o.value).indexOf($) + 1; $ += $);
			r.setEndPoint("StartToEnd", s), r.text = $ + r.text, end = o.value.indexOf($);
			s.text = $, start = o.value.indexOf($);
			if(d.execCommand && d.queryCommandSupported("Undo"))
				for(r = 3; --r; d.execCommand("Undo"));
			return o.value = value, this.setCaret(start, end), {start: start, end: end};
		}
		return {start: 0, end: 0};
	};
	o.getText = function(){
		var o = this.getCaret();
		return this.input.value.slice(o.start, o.end);
	};
	o.setText = function(text){
		var o = this.getCaret(), i = this.input, s = i.value;
		i.value = s.slice(0, o.start) + text + s.slice(o.end);
		this.setCaret(o.start += text.length, o.start);
	};
	new function(){
		var d = document, o = d.createElement("input"), s = Selection;
		s.isStandard = "selectionStart" in o;
		s.isSupported = s.isStandard || (o = d.selection) && !!o.createRange();
	};
}


Example

<form id="form">
	<fieldset>
		<legend>Selection Test</legend>
		<textarea name="text" rows="10" cols="30">
www.jsfromhell.com
Jonas Carlos Lalala
Bin Laden x Bush
		</textarea><br />
		<input name="getText" type="button" value="[Get selected text]" />
		<input name="getSel" type="button" value="[Get cursor]" />
		<br /><input name="setText" type="button" value="[Set selected text]" />
		<input name="setSel" type="button" value="[Set cursor]" />
	</fieldset>
</form>

<script type="text/javascript">
var f = document.forms.form;
var selection = new Selection(f.text);

f.getText.onclick = function(){
	alert(selection.getText());
	f.text.focus();
};
f.setText.onclick = function(){
	var s = prompt("New text:", selection.getText());
	s !== null && selection.setText(s);
	f.text.focus();
};
f.getSel.onclick = function(){
	var s = selection.getCaret();
	alert("Start: " + s.start + "\nEnd: " + s.end);
	f.text.focus();
};
f.setSel.onclick = function(){
	var s = selection.getCaret();
	selection.setCaret(+prompt("Start:", s.start) || 0, +prompt("End:", s.end) || 0);
	f.text.focus();
};
</script>

CSV Parser / Writer for PHP

CSV Parser / Writer

Example A:

//cell separator, row separator, value enclosure
$csv = new CSV(';', "\r\n", '"');

//parse the string content
$csv->setContent(file_get_contents('data.csv'));

//returns an array with the CSV data
print_r($csv->getArray());



Exemple B:

$csv = new CSV(';', "\r\n", '"');
//sets up the content through an array
$csv->setArray(
	array(
		array('col"una1', "colu\r\nna2"),
		array('col;una3', 'coluna4')
	)
);
//retorns string with the CSV representation
print $csv->getContent();



<?php
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
class CSV{
	var $cellDelimiter;
	var $valueEnclosure;
	var $rowDelimiter;

	function CSV($cellDelimiter, $rowDelimiter, $valueEnclosure){
		$this->cellDelimiter = $cellDelimiter;
		$this->valueEnclosure = $valueEnclosure;
		$this->rowDelimiter = $rowDelimiter;
		$this->o = array();
	}
	function getArray(){
		return $this->o;
	}
	function setArray($o){
		$this->o = $o;
	}
	function getContent(){
		if(!(($bl = strlen($b = $this->rowDelimiter)) && ($dl = strlen($d = $this->cellDelimiter)) && ($ql = strlen($q = $this->valueEnclosure))))
			return '';
		for($o = $this->o, $i = -1; ++$i < count($o);){
			for($e = 0, $j = -1; ++$j < count($o[$i]);)
				(($e = strpos($o[$i][$j], $q) !== false) || strpos($o[$i][$j], $b) !== false || strpos($o[$i][$j], $d) !== false)
				&& $o[$i][$j] = $q . ($e ? str_replace($q, $q . $q, $o[$i][$j]) : $o[$i][$j]) . $q;
			$o[$i] = implode($d, $o[$i]);
		}
		return implode($b, $o);
	}
	function setContent($s){
		$this->o = array();
		if(!strlen($s))
			return true;
		if(!(($bl = strlen($b = $this->rowDelimiter)) && ($dl = strlen($d = $this->cellDelimiter)) && ($ql = strlen($q = $this->valueEnclosure))))
			return false;
		for($o = array(array('')), $this->o = &$o, $e = $r = $c = 0, $i = -1, $l = strlen($s); ++$i < $l;){
			if(!$e && substr($s, $i, $bl) == $b){
				$o[++$r][$c = 0] = '';
				$i += $bl - 1;
			}
			elseif(substr($s, $i, $ql) == $q){
				$e ? (substr($s, $i + $ql, $ql) == $q ?
				$o[$r][$c] .= substr($s, $i += $ql, $ql) : $e = 0)
				: (strlen($o[$r][$c]) == 0 ? $e = 1 : $o[$r][$c] .= substr($s, $i, $ql));
				$i += $ql - 1;
			}
			elseif(!$e && substr($s, $i, $dl) == $d){
				$o[$r][++$c] = '';
				$i += $dl - 1;
			}
			else
				$o[$r][$c] .= $s[$i];
		}
		return true;
	}
}
?>

ProbabilityRandom //PHP Class


Class to return items based on their probability.

Updated version can be found here


usage
$prExample = new ProbabilityRandom;

$prExample->add( 'I have more chances than everybody :]', 30 );
$prExample->add( 'I have good chances', 10 );
$prExample->add( 'I\'m difficult to appear...', 1 );

for( $x=10; $x--; print $prExample->get() . '<br />' );


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
class ProbabilityRandom {
	#private vars
	var
		$data = array(),
		$universe = 0;

	#add an item to the list and defines its probability of being chosen
	function add( $data, $probability ){
		$this->data[ $x = sizeof( $this->data ) ] = new stdClass;
		$this->data[ $x ]->value = $data;
		$this->universe += $this->data[ $x ]->probability = abs( $probability );
	}

	#remove an item from the list
	function remove( $index ){
		if( $index > -1 && $index < sizeof( $this->data ) ) {
			$item = array_splice( $this->data, $index, 1 );
			$this->universe -= $item->probability;
		}
	}

	#clears the class
	function clear(){
		$this->universe = sizeof( $this->data = array() );
	}

	#return a randomized item from the list
	function get(){
		if( !$this->universe )
			return null;
		$x = round( mt_rand( 0, $this->universe ) );
		$max = $i = 0;
		do
			$max += $this->data[ $i++ ]->probability;
		while( $x > $max );
		return