RSS

Tag Archives: javascript

Inspect a list of filenames (js)

This shortcut demonstrates the power of some ES6 features.

Given a list of filenames, a map function is applied onto the array to generate (another) array of objects. Arrow functions and parentheses (to return JSON objects) are the trick used to add properties “on the fly”.
The resulting object will have the name, path and stats information resolved.

https://bitbucket.org/snippets/pirraste/8eG956/filesniffjs

Advertisements
 
Leave a comment

Posted by on 2018/04/20 in dev

 

Tags: , ,

Promises rejection (..but with style)

I find handy define this kind of function in my code:

function if_error(reject, err) {
  if (err) {
    console.error(err);
    reject(err);
  }
}

Now when I’ll need to handle a rejection, my code will be

something.can('go-wrong', (err) => {
  if_error(reject, err);
  ...

It’s something between pure functional programming and very readable code.

 
Leave a comment

Posted by on 2017/05/16 in dev

 

Tags: ,

js timestamp

Sometimes while logging js I need to have a timestamp in the beggining of the row. There are libraries to manage timestamps and to print wonderful logs, but sometimes the needs are only to make some console.log while debugging.

This is my one-line way to handle it:

function timestamp() {
  return (new Date).toISOString().match(/([0-9]{2}:[0-9]{2}:[0-9]?[0-9].[0-9]{3})/g)[0];
}

or “keep only the time part of an ISO formatted timestamp”.

 
Leave a comment

Posted by on 2016/12/16 in dev

 

Tags: , ,

this.window (& friends)

Open a console in your browser, then verify these:

console.log(this === this.window); // true
console.log(this === this.window.window.window); // true
console.log(this === this.self); // true 
console.log(this === this.frames); // true (also when this.frames.length > 0)

When this.frames.length > 0 you can also:

for (i in this.frames) console.log(this === this.frames[i]) // true,false,true,true,false,.... (so many true because we have "self","window","parent","frames",... The others are $,jQuery,google stuff,...)

console.log(this.window[0] === this.window[1]); // false
console.log(this.window[0] === this); // false (obviously in my test)
console.log(this.window[1] === this); // false (obviously in my test)
console.log(this.window[1] === this.frames[1]); // true
 
Leave a comment

Posted by on 2016/04/07 in dev

 

Tags: , , ,

Show me your events

“Which javascript event best fits my requirements?”

To answer the question let’s inspect the given element and get all its bound events:

var evts = ‚Äč$._data( $("#element")[0], "events" );

Easy as an easy thing!

 
Leave a comment

Posted by on 2014/06/04 in dev

 

Tags: ,

Javascript as C# code

One of the most handy things I created during my daily job as a .NET developer is a system to automagically include my javascript code libraries into every new project I’m going to develop. It’s a sort of javascript dll…no wait IT ACTUALLY IS a .dll file! =)
Here’s the trick…

Preparing the recipe

  • Create a new library (.dll) project … name it “My.Common.Js” (it’s just an example)
  • Include your javascript file (i.e. “myJsFile.js“) into the project
  • Include a folder that contains the minified version of the script (something like “minified/myJsFile.min.js“) into the project
  • Right click on the “myJsFile.min.js” and choose: Build Action “Embedded Resource”

Mix them all

Into the .cs file include the following (at the top, under the “using” block):

[assembly: WebResource("My.Common.Js.minified.myJsFile.min.js", "application/x-javascript")]

Let’s define a class that uses these files:

namespace My.Common
{
    public class JsUtil
(..)

The JsUtil class has one interesting private function that takes the name of a resource and create its phisical file into the given path, including its inclusion (sorry for the joke) into the given page:

private static void dumpResource(Page p, String rezname, String path, String inclPath, Boolean toTheEnd)
{
  String jsns = "My.Common.Js.minified.";
 
  // fix path
  if (!path.EndsWith(@"\")) path += @"\";
  if (!inclPath.EndsWith(@"/")) inclPath += @"/";
  String fout = path + rezname;
  String version = "?ver=1";

  // recreate the file only if needed
  if (!System.IO.File.Exists(fout))
  {
    // read the embedded resource
    String rez = String.Empty;
    System.Reflection.Assembly a = System.Reflection.Assembly.GetAssembly(typeof(JsUtils));
    Version v = a.GetName().Version;
    version = "?ver=" + v.Build.ToString();
    using (StreamReader sr = new StreamReader(a.GetManifestResourceStream(jsns + rezname)))
    {
      rez = sr.ReadToEnd();
    }

    // write it into a file
    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
    try
    {
      using (StreamWriter sw = new StreamWriter(fout))
      {
        sw.Write(rez);
      }
    }
    catch
    {
      // we're racing...let them win
    }
  }

  // include it into the page 
  System.Web.UI.HtmlControls.HtmlGenericControl headctrl = new System.Web.UI.HtmlControls.HtmlGenericControl("script");
  headctrl.Attributes.Add("type", "text/javascript");
  headctrl.Attributes.Add("src", inclPath + rezname + version);
  if (toTheEnd || p.Header.Controls.Count == 0)
    p.Header.Controls.Add(headctrl);
  else
    p.Header.Controls.AddAt(0, headctrl);
}

Ok, now it’s easy. My JsUtil class exposes a very minimal static method:

public static void Include_myJsFile(System.Web.UI.Page page, String jsPath, String inclPath)
{
  dumpResource(page, "myJsFile.min.js", jsPath, inclPath, true);
}

Serve hot

Somewhere in your page:

// filesystem path
String filepath = HttpContext.Current.Server.MapPath("~") + @"\JS\my.common";
// js path
String includepath = @"../JS/my.common"; // js format
// check
if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath);
// include
JsUtils.Include_myJsFile(this, filepath, includepath);
 
Leave a comment

Posted by on 2013/12/27 in dev

 

Tags: , , , ,

true or false: it’s not a binary choice

When using javascript functions like the Array Filter Method you need to define a test over a value.
Sometimes I see that developers are confused about “what’s true” and this can generate bugs.

Let’s work with an example.
Given a function that makes some test over a parameter:

// be careful: uneval() is a Firefox non-standard feature
function doTheTest(val) {
    console.log("------------- val " + uneval(val) + " is " + typeof (val));

    if (val)  console.log('val is pseudo true');
    else console.log('val is not pseudo true');
    
    if (val == true)  console.log('val is == true' );
    else console.log('val is not == true');
    
    if (val === true)  console.log('val is === true' );
    else console.log('val is not === true');
    
    if (val != true)  console.log('val is != true' );
    else console.log('val is not != true');
    
    if (val !== true)  console.log('val is !== true' );
    else console.log('val is not !== true');

    // ..and null?
    if (val == null)  console.log('val is == null' );
    else console.log('val is not == null');
    if (val === null)  console.log('val is === null' );
    else console.log('val is not === null');
}

let’s call that function with some “stuff”:

doTheTest(42);
doTheTest(0);
doTheTest("one");
doTheTest("");
doTheTest(null);
doTheTest(); // undefined
doTheTest({a:1, b:11});
doTheTest(doTheTest); // =)

This is the Firebug’s console output, with some highlight from me:

------------- val 42 is number
val is pseudo true            <==
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val 0 is number
val is not pseudo true            <==
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val "one" is string
val is pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val "" is string
val is not pseudo true            <==
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val null is object
val is not pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is == null
val is === null
------------- val (void 0) is undefined
val is not pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is == null            <==
val is not === null
------------- val ({a:1, b:11}) is object
val is pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val function doTheTest(val) { ..code removed.. } is function
val is pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null

Did you expect these results?

 
Leave a comment

Posted by on 2013/11/06 in dev

 

Tags: , , , , , ,