How to convert a function definition as string to code in JavaScript

 

Just a snippet for converting a function as string to code:

image

 

Code

<!doctype html>
<html>
<head>
    <meta charset=”utf-8″ />
    <meta http-equiv=”x-ua-compatible” content=”ie=edge”>
    <title>Research</title>
    <meta name=”description” content=”A page to quickly spike some code or styling.”>
    <meta name=”viewport” content=”width=device-width, initial-scale=1″>
    <link rel=”icon” href=”data:;base64,iVBORw0KGgo=”>   
    <style>
       
    </style>
</head>
<body>
    <script>
        // Define a function as a string.
        // Don’t forget the “(” and the “)” arround the function.
        // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
        var functionAsString = “(function(a, b){ return a + b; })”;

        // Convert a string containing a function definition to a real function.
        var fn = eval(functionAsString);

        // Execute the created function.
        var result = fn(1, 2);

        // Log result is: 3
        console.log(result);
    </script>
</body>
</html>

JavaScript tip from Rob Eisenberg: use the web standards as much as possible.

 

Just a good tip from Rob Eisenberg:
Write your JavaScript code in vanilla (standard) JavaScript as much as possible, even your framework code, because the web standards will be there, when your pick of the day framework will be long gone.
Your code base will be much more long lived and you will have less trouble, when migrating to a newer version of a framework or a complete other framework.

ES6 modules

Just some reminders, when working with ES6 modules:

  • ES6 modules are automatically strict-mode code, even if you don’t write "use strict"; in them.
  • When you run a module containing an import declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.

More information on ES6 modules:

Exclude file paths from jshint with gulp

If you want to jshint all JavaScript files in a folder, but want to exclude a subfolder, you can use “negation” in gulp.

 

 

var gulp = require("gulp");

var jshint = require("gulp-jshint");
var plumber = require("gulp-plumber");

 

var onError = function (err) {
        console.log(err);
    };

/**
     * Hint all of our custom developed Javascript files.
     */
    gulp.task("jshint", function () {

        return gulp.src([
            "Client/**/*.js",
           "!Client/Libraries/**/*.js"
        ])
        .pipe(plumber({
            errorHandler: onError
        }))
        .pipe(jshint())
        .pipe(jshint.reporter("default"));
    });

How to live reload a css file, without reloading the whole page, by using gulp-livereload.

 

If you want to only reload css and not the entire page, when files change on disk, you can use the following gulp file.

 

/** * When you want to use this gulpfile.js, make sure you execute the gulp.ps1 PowerShell script first, so everything is installed correctly. */ (function (require) { "use strict"; // Gulp. var gulp = require("gulp"); // Gulp plugins. var plumber = require("gulp-plumber"); var livereload = require("gulp-livereload");

// Gulp plumber error handler var onError = function (err) { console.log(err); }; /** * The following file will be reloaded, when one of the "watched" *.html or 8.js files has changed. */ gulp.task('reload', function () { gulp.src([ "App/unit.test.runner.html" ]) .on('error', onError) .pipe(gulp.dest('dist')) .pipe(livereload()); }); /** * All *.css files will be reloaded, when one of the "watched" *.css files has changed. */ gulp.task('reloadCss', function () { gulp.src([ 'App/**/*.css' ]) .on('error', onError) .pipe(gulp.dest('dist')) .pipe(livereload()); }); /** Watch *.css files, but only reload css, not the entire page. Watch *.html and *.js files, when a change is detected, reload the whole page. */ gulp.task("watch", function () { livereload.listen(); gulp.watch([ "App/**/*.css" ], ["reloadCss"]); gulp.watch([ "App/**/*.html", "App/**/*.js" ], ["reload"]); }); /** When the user enters "gulp" on the command line, the default task will automatically be called. This default task below, will run all other task automatically. So when the user enters "gulp" on the command line all task are run. */ gulp.task("default", ["watch", "reload"]); }(require));

Pretty print json unit test error results with Jasmine

 

 

 

If you use the standard HTML reporter for jasmine an expect like:

expect(JSON.stringify(actual)).toEqual(JSON.stringify(expected));

would result in:

 

image

If you replace the div tag with a pre tag in the “jasmine-html.js” file.

image

 

 

and use the third paramater of the JSON.stringify method to pretty print the JSON,

like:

expect(JSON.stringify(actual, null, 4)).toEqual(JSON.stringify(expected, null, 4));

 

the result will be:

image

 

In some cases this will simplify, spotting the error in the JSON result.

One of the most important things to remember: In C# and JavaScript, object references are passed to functions by value not by reference

By default C# and JavaScript pass object references by value not by reference, but what does that mean?

Well if you assign an object to a variable, this variable is just a pointer to that object in memory.

(Examples in C#)

var person = new Person
{
Id = 2,
Name = "John"
};

The variable person is just a pointer to the object in memory, the memory contains the object { Id = 2, Name = “John”}

When passed to a function, a copy of this pointer is supplied to the function, not the object itself.

So when you update properties of the object in the function, the variable outside the function will get updated.

 

But when you set the object to NULL in the function, the variable outside the function will NOT be set to NULL.

 

In C# you can override this by adding the “ref” keyword before the parameter, in that case the pointer of the variable will be passed and thus setting the object to null in the function will set the variable outside the function to NULL.

 

Some unit test to explain this:

namespace Test
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;      
[TestClass]
public class Research
{
[TestMethod]
public void Update_object_properties_should_update_variable()
{
var person = new Person
{
Id = 2,
Name = "John"
};
UpdateObjectProperties(person);
Assert.IsTrue(person.Name == "Mike");
}
public void UpdateObjectProperties(Person person)
{
person.Name = "Mike";
}
[TestMethod]
public void Update_object_pointer_should_not_update_variable()
{
var person = new Person
{
Id = 2,
Name = "John"
};
UpdateObjectPointer(person);
Assert.IsTrue(person.Name == "John");
}
public void UpdateObjectPointer(Person person)
{
person = null;
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}

 

image

 

More info can be found at:

http://stackoverflow.com/questions/9717057/c-sharp-passing-arguments-by-default-is-byref-instead-of-byval

http://jonskeet.uk/csharp/parameters.html

http://jonskeet.uk/csharp/references.html