Tag Archives: Computer science

Flexible JavaScript – Splitting Strings

After reviewing a chunk of my code for today I continue to admire the flexibility of JavaScript. It’s really powerful. In that example you can get a string split it by a given symbol to an array and than get the Nth element of it. All this on one line! Amazing!

var str = 'my-long-string';
str.split('-')[0]; // will contain "my"

the 1st and 2nd indexes contain respectively “long” and “string”!

Which Model Should Contain That Method?

Let’s say you have two models – each one modeling a database table – Users & Article. Here there’s nothing to deal with Zend Framwork, but you can think of them as typical models in a ZF application.

What happens if you have to write a getUserArticles method? Where would you put it? Whether this will be the User model or the Article model?Where?

Although technically you can put it in both models my advice is to look at the SQL query. If the FROM clause is containing the user table – than put the method in the User model, but here you’d have something like:

SELECT * FROM Article WHERE user_id = 1

I’d prefer to place it in the Article model!

Friday Algorithms: JavaScript Merge Sort

Merge Sort

This week I’m going to cover one very popular sorting algorithm – the merge sort. It’s very intuitive and simple as it’s described in Wikipedia:

  • If the list is of length 0 or 1, then it is already sorted. Otherwise:
  • Divide the unsorted list into two sublists of about half the size.
  • Sort each sublist recursively by re-applying merge sort.
  • Merge the two sublists back into one sorted list.

Here’s the Source

(JavaScript)

var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];
 
function mergeSort(arr)
{
    if (arr.length < 2)
        return arr;
 
    var middle = parseInt(arr.length / 2);
    var left   = arr.slice(0, middle);
    var right  = arr.slice(middle, arr.length);
 
    return merge(mergeSort(left), mergeSort(right));
}
 
function merge(left, right)
{
    var result = [];
 
    while (left.length && right.length) {
        if (left[0] <= right[0]) {
            result.push(left.shift());
        } else {
            result.push(right.shift());
        }
    }
 
    while (left.length)
        result.push(left.shift());
 
    while (right.length)
        result.push(right.shift());
 
    return result;
}
 
console.log(mergeSort(a));

It’s interesting to see what happens in the Firebug’s console:

[34, 203, 3, 746] [200, 984, 198, 764, 9]
 
[34, 203] [3, 746]
 
[34] [203]
 
[3] [746]
 
[200, 984] [198, 764, 9]
 
[200] [984]
 
[198] [764, 9]
 
[764] [9]
 
[3, 9, 34, 198, 200, 203, 746, 764, 984]

Actually the tricky part in this algorithm is the merge function – it does all the work.

Zend_View_Helper_InlineScript Appends Scripts Twice

Double Trouble

duplicate
This is a well known problem, which is well described as a bug in Zend Framework’s issue tracker. Once you add some scripts with the inlineScript helper you’ll receive them twice in the code. This makes the page slower and leads to some crashes.

$scripts->appendFile('my-file1.js')
        ->appendFile('my-file2.js')
        ->appendScript('alert("test")');

This will print the alert twice.

<script src="my-file1.js"></script>
<script src="my-file2.js"></script>
<script>
//<!--
alert("test");
//-->
</script>
<script>
//<!--
alert("test");
//-->
</script>

Quick Solution

Although this is the worst solution I’ve ever made – it works! There is a check for duplicates in the HeadScript helper around line 240:

if (!$this->_isDuplicate($content)) {
...

and then a check in the _isDuplicate method(), ~ line 270:

if (($item->source === null)
    && array_key_exists('src', $item->attributes)
    && ($file == $item->attributes['src']))
{
    return true;
}

The thing you’ve to do is to add such a check for the appendScript() and not only for appendFile() method – again ~ line 230:

case 'script':
	if (!$this->_isDuplicate($content)) {
	    $item = $this->createData($type, $attrs, $content);
	    if ('offsetSet' == $action) {
	        $this->offsetSet($index, $item);
	    } else {
	        $this->$action($item);
	    }
	}
	break;

And then slightly modify the _isDuplicate method:

foreach ($this->getContainer() as $item) {
    if (($item->source === null)
        && array_key_exists('src', $item->attributes)
        && ($file == $item->attributes['src']))
    {
        return true;
    }
    if ($item->source == $file) {
        return true;
    }
}
return false;

Zend Framework: Inject JavaScript Code in a Action/View

There is a view helper that can inject a head or inline script into your code.

Simply by putting some JavaScript code into the view script wont do the job, because the .phtml file is grabbed and parsed by the Zend Framework and thus the code there wont be parsed as JavaScript and it wont be executed as well by the browser.

The Most Simple Way …

is to put some place holder into the layout .phtml file and than from the controller’s action you can assign some JS code:

// layout.phtml
<?php
...
echo $this->layout()->scriptTags;
...
<?php
 
class IndexController extends Zend_Controller_Action
{
	public function indexAction() 
	{
		$this->view->layout()->scriptTags = '<script src="my.js"></script>';	
	}	
}

Solution No. 2

Although the first solution is correct it’s not the most clearest way, because you put the JavaScript code into the PHP, and this sooner or later becomes a mess.

<?php
 
class IndexController extends Zend_Controller_Action
{
	public function indexAction() 
	{
		$this->view->layout()->scriptTags = '<script src="my.js"></script>';
						  . '<script>alert("here\'s my" + "test")</script>';
	}	
}

The IDE is not highlighting the code, and you’ve to deal with too many quotes, which is bad! There is a better solution however – the inline script:

// script tags
/* @var $scripts Zend_View_Helper_InlineScript */
$scripts = $this->view->inlineScript();
$scripts->appendFile('my.js');

Simply the Best

Yeah, the best solution is something even better than the second one. Although the solution I’ve just mentioned is fine for including JS files, when you’ve to add some JS code you’ll have to put it again into the PHP.

$msg = 'some dynamically generated message';
 
// script tags
/* @var $scripts Zend_View_Helper_InlineScript */
$scripts = $this->view->inlineScript();
$scripts->appendFile('my.js');
$scripts->appendScript('alert("' . $msg . '")');

If there’s no relation between JavaScript and PHP you can simply put all this code into a separate .js file and load it from there. This is by the way the best solution because the file is cached by the browser, if the cache is enabled. But most of the time you perhaps have to send some variables from PHP to the JavaScript code.

It would be perfect if you had some kind of a variable placeholders – exactly as you have it in the Zend Framework’s view scripts!

Another View

This is completely possible – just forget about the default view – it renders the view script and it’s bind to the /views/scripts folder. You can make another, completely new, view instead! Here’s some source:

$view = new Zend_View();
$view->setBasePath('path_to_the_js_folder');
 
$view->msg = 'Some dynamically generated message';
 
// script tags
/* @var $scripts Zend_View_Helper_InlineScript */
$scripts = $this->view->inlineScript();
$scripts->appendFile('my.js');
$scripts->appendScript($view->render('inline.js'));

Thus now in the JS file you can have some placeholders!

// inline.js
 
// some js code
// ...
alert('<?php echo $this->msg ?>');