Wednesday, July 24, 2013

vkThread - execute any js function in a thread.

vkThread is a javascript plugin, which allows you to execute any function of a your code in a thread.

Standalone function: simply pass it as an argument to the vkthread(), and get the result in a callback function. You don't need to create a separate file for each thread, like you normally do with a regular worker.

Object's method: vkthread accepts context as an optional parameter and executes function in its context. Simply pass the object as a context, that's it.

Function with dependencies: vkthread accepts a list of filenames as an optional argument and imports these files in the thread before the function is calling.

Here is a basic example:


function sum(num1, num2) {
    return num1 + num2;
}

/* execute function foo() in the main thread. */
var foo = sum(2,3);

/* open a new thread and execute function foo() in this thread. */
vkthread.exec(sum, [2,3], function(data){ var foo = data; });



vkThread is based on HTML5 "Worker" technology. It also incorporates JSONfn code to implement key tasks. In spite of technical complexity, plugin is super compact. Development version (plain text with comments) is less than 2k. I don't care to minify it.

For examples and documentation see http://www.eslinstructor.net/vkthread/

Monday, November 12, 2012

heredoc in javascript

Javascript doesn't have built-in  "heredoc" operator or feature. So, if we need it, we have to implement it by ourself. Here is one of possible way to implement heredoc-style functionality.

1. To prevent javascript from checking syntax and issuing errors we create desired string as a comment within a function body:

var foo = function(){/*
blah blah blah
*/};  

2. Use built-in "toString()" function to extract this string:

var bar = foo.toString();

But toString() returns everything, not only function body:
"function (){/*blah blah blah/*}"
So, we need to extract only the part we need. I can suggest 2 possible ways:

a) foo.toString().slice(14, -3);
b) foo.toString().split(/\n/).slice(1, -1).join('\n');

if you select the second version, you must start and end your string with new line:
function (){/*
blah
blah blah
*/}

Generic functions:
1)
function heredoc(fn) {
return fn.toString().slice(14, -3);
}

2)
function heredoc(fn) {

return fn.toString().split(/\n/).slice(1, -1).join('\n');
}


There is no difference in performance between these two solutions. I prefer the first one as it looks  more simple, and short strings can be written in one line. But it matter of test.

Usage:

var foo = function(){/*
blah
blah blah

*/}; 


var bar = heredoc(foo);



console.log(bar); // blah 
                            blah blah

------------------------------------------------------------------------------------

Enjoy.
var zzz = function(){/*
var xxx
 = 
 
var zzz = function(){/*
var xxx
 = 
 'aaa';*/};var zzz = function(){/*
var xxx
 = 
 'aaa';*/};

Tuesday, August 21, 2012

Convert Javascript Object with Functions to String and String to Object

A lot of javascript developers want to serialize object and save it on server or local storage, in order to take this string later and convert it back into an object. It's not a big deal if your object has only member variables. You simply use javascript native JSON object to serialize/parse  your custom object.
But it doesn't work if your object has member function. Native JSON ignores functions. Recently I made a brief search and wasn't able to find acceptable way to manage this problem. So, I spent some time on development a very small plugin, which can help many developers to create simple and elegant applications. All plugin is just 20 lines of code, so I show it right here

----------------------------------------------------------------------------
var JSONfn;
if (!JSONfn) {
    JSONfn = {};
}
(function () {
JSONfn.stringify = function(obj) {
return JSON.stringify(obj,function(key, value){
return (typeof value === 'function' ) ? value.toString() : value;
});
}
JSONfn.parse = function(str) {
return JSON.parse(str,function(key, value){
if(typeof value != 'string') return value;
return ( value.substring(0,8) == 'function') ? eval('('+value+')') : value;
});
}
}());
------------------------------------------------------------------------------------------


       var str = JSONfn.stringify(obj);
var obj = JSONfn.parse(str);

See live demo at http://www.eslinstructor.net/jsonfn/

Enjoy!



Sunday, February 19, 2012

pretty-data

pretty-data is a small, simple and powerfull nodejs plugin to beautify ( pretty print ) or minify XML, JSON or CSS text.
This script also has client-side version known as vkBeautify


see demo at:   http://www.eslinstructor.net/pretty-data/

get source from:  https://github.com/vkiryukhin/pretty-data

Sunday, January 22, 2012

vkBeautify - XML, JSON or CSS Beautifier

http://www.eslinstructor.net/vkbeautify/

vkBeautify is a small, simple and powerfull javascript plugin to beautify XML, JSON or CSS text.
This script works either as a client-side javascript or as a nodeJS plagin.

Consider to use it if you:
  • create  XML, JSON or CSS  text manually at client side
  • create  XML, JSON or CSS  with tool, but let user to check or edit the result manually
  • get  XML, JSON or CSS  data from web service and check or edit it before or after processing the data
  • other cases when you need to create, edit or check content of an  XML, JSON or CSS  file.
This plugin:
  1. less then 2k if minified
  2. has only one function
  3. takes less then 5 mSec to process 50K text
    ( Celeron 2.2 GHz, 2.0GB, any of 3 major browsers) 

Saturday, November 5, 2011

Smartupdater 4.0.beta is released


http://www.eslinstructor.net/smartupdater/

New features:  100%-jQuery API style.
No new functionality was added in this release. Only new API and coding style were implemented.

Saturday, October 1, 2011

Strict Mode Compatible Micro-Templating Engine


Recently I developed and published jQuery templating plugin http://www.eslinstructor.net/vktemplate/, which is built on very popular Micro-Templating engine written by John Resig. It is a super compact, simple to use and power templating solution. I enjoy to use it.
But... one thing I want to avoid. The thing is the "with()" statement. There are two reasons.

1. The first, and most important reason is the fact, that using "with()" is not recommended, and is forbidden in ECMAScript 5 strict mode.

2. The second reason is performance. Performance can be decreased  if we intencively access objects other then the object specified with the "with()" statement.

Here is the  version of the  ECMAScript 5's strict mode compatible Micro-Templating engine which I created and breefly tested a couple of days ago.


1 function _tmpl(str, data){ 
2 var fn = new Function("o",
3 "var p=[],print=function(){p.push.apply(p,arguments);};" +
4 " p.push('" +
5 str.replace(/[\r\t\n]/g, " ")
6 .replace(/'(?=[^%]*%>)/g,"\t")
7 .split("'").join("\\'")
8 .split("\t").join("'")
9 .replace(/<%=(.+?)%>/g, "',$1,'")
10 .replace(/<%=(.+?)%>/g, "',this.$1,'")
11 .split("<%").join("');")
12 .split("%>").join("p.push('")
13 + "');    return p.join('');");
14 return fn( data );
15 };

Of course, if we remove with() statement, we must explicetly refer to the object which otherwise would be specified with "with()" statement. So, we have to change our template notation:

{name:"john"}
<%= o.name %>
<% if( o.name ) {...} %>

In this notation "o" is related to the function's argumen at line #2 of the example above.

Pro: no forbidden "with()" statement, better performance and better code readability as template-related variables are shown explicetely with object notation and not mixed other javascript variables.

Con: a couple of extra characters per each object's variables.

Next week I gonna to finish testing  and apply this with-free solution to my current plugin.