Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

ES6 Reflect API

| Comments

What is the reflect object all about?

ES6's Reflect object is a single ordinary object that contains methods related to Ecmascript 6 reflection API.

The below are some key points that one must be aware of before using them.

  • It's not a function object.

  • It does not have a [[Construct]] internal method. (Can't use new)

  • It does not does not have a [[Call]] internal method. (Can't invoke it as a function)

What are all the methods that Reflect object has?

  • Reflect.get(target, name, [receiver])

  • Reflect.set(target, name, value, [receiver])

  • Reflect.has(target, name)

  • Reflect.apply(target, receiver, args)

  • Reflect.construct(target, args)

  • Reflect.getOwnPropertyDescriptor(target, name)

  • Reflect.defineProperty(target, name, desc)

  • Reflect.getPrototypeOf(target)

  • Reflect.setPrototypeOf(target, newProto)

  • Reflect.deleteProperty(target, name)

  • Reflect.enumerate(target)

  • Reflect.preventExtensions(target)

  • Reflect.isExtensible(target)

  • Reflect.ownKeys(target)

Why reflect?

The above list, looks very familiar to the methods defined in Object but on of the major difference is that the Reflect object's method does return meaningful data rather than throwing an error in case of failure.

Let's see few examples to understand more about it:

1
2
3
4
5
6
try {
  Object.defineProperty(obj, name, desc);
  // worked.
} catch (e) {
  // bombed.
}

With reflect:

1
2
3
4
5
if (Reflect.defineProperty(obj, name, desc)) {
  // worked
} else {
  // bombed
}

Same structure applies for:

  • Reflect.set (to update a property).

  • Reflect.deleteProperty (to delete a property).

  • Reflect.preventExtensions (to make an object non-extensible).

  • Reflect.setPrototypeOf (to update an object's prototype link).

Reflect.has(obj, name) equivalent of (name in obj) and Reflect.deleteProperty(obj, name) equivalent to delete obj[name], but both of these reflect APIs are first-class functions.

We would use apply method on a function fn with a variable number of arguments packed as an array args and binding the this value to an obj as fn.apply(obj, args) but if fn has defined it's own apply method we need to invoke Function.prototype.apply.call(fn, obj, args) to make sure that built-in is invoked, but the same can be simplified to Reflect.apply(fn, obj, args)

Proxy and Reflect gel well:

There is a one-to-one correspondence between "reflect" methods and Proxy traps which ensures that the return type to be compatible with the return type of the Proxy traps.

1
2
3
4
5
var life = Proxy.create({
  get: function(target, name, receiver) {
    return Reflect.get(target, name, receiver);
  }
});

Where can I use Reflect now?

As of now you can use this in IE Technical Preview or use polyfills like echo-js or harmony-reflect

References:

Custom Elements With ES6

| Comments

Custom Elements play an important role in Web Components spectrum. Here’s a list that talks about why we need them:

  • Define new DOM elements.

  • Extending from other elements.

  • Extending DOM APIs.

  • Providing custom functionality to a single tag.

A custom element is made up of a local name, namespace, prototype and lifecyle callbacks.

After creating the custom element, the element definition is added to a registry using the document.registerElement() method. The lifecycle of a custom element is listed below:

  1. Custom element is created before its definition is registered.

  2. Definition of a custom element is registered.

  3. Custom element instance is created after its definition was registered.

  4. Custom element is inserted into active document.

  5. Custom element is removed from active document.

  6. Custom element’s attribute is created, removed, or modified.

Creating custom element with ES6 is easy using it's class feature, but it's important to note that the only subclassing that works is of your own classes, we can't subclass builtins or platform objects, the issues are about allocation of the object (especially for DOM objects), about passing arguments to the superconstructor (arbitrary arguments) --- DOM objects don't really have callable constructors right now, so until the DOM catches up with ES6 specs we need to deal with these limitations.

Luckily, we could pass the extended element to registerElement because it's implementation looks at the passed object's prototype property!

It's even more important to note that expect IE (that too to a very small extent) none of the browsers have implemented classes and we will have to use transpilers like 6to5 or Google's Traceur.

Ok, enough of theory and drawbacks let's see some code!

Basic boilerplate:

1
2
3
4
5
6
7
8
9
10
11
class CustomElement extends HTMLElement {
    // Fires when an instance of the element is created.
    createdCallback() {};
    // Fires when an instance was inserted into the document.
    attachedCallback() {};
    // Fires when an instance was removed from the document.
    detachedCallback() {};
    // Fires when an attribute was added, removed, or updated.
    attributeChangedCallback(attr, oldVal, newVal) {};
}
document.registerElement('custom-element', CustomElement);

Now, let's try extending the HTMLSpanElement (interface).

1
2
3
4
5
6
class DateSpan extends HTMLSpanElement {
   createdCallback(){
     this.textContent = "Today's date: " + new Date().toJSON().slice(0,10);
   }
}
document.registerElement('date-today', DateSpan);

Transplied code with 6to5 would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"use strict";

var _inherits = function (child, parent) {
  child.prototype = Object.create(parent && parent.prototype, {
    constructor: {
      value: child,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (parent) child.__proto__ = parent;
};

var DateSpan = (function () {
  var _HTMLSpanElement = HTMLSpanElement;
  var DateSpan = function DateSpan() {
    if (_HTMLSpanElement) {
      _HTMLSpanElement.apply(this, arguments);
    }
  };

  _inherits(DateSpan, _HTMLSpanElement);

  DateSpan.prototype.createdCallback = function () {
    this.textContent = "Today's date: " + new Date().toJSON().slice(0, 10);
  };

  return DateSpan;
})();

document.registerElement("date-today", DateSpan);

See <date-today></date-today> working:

Well, it was a silly little custom span element, let's make a better one.

One of favs, <xkcd-img> </xkcd-img> :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class XKCD extends HTMLImageElement {
    constructor(){}
    createdCallback() {
      var xhr = new XMLHttpRequest()
      xhr.open('GET','http://xkcd-imgs.herokuapp.com/')
      xhr.onload = function(data){
        this.style.backgroundImage = `url('${JSON.parse(data.target.response).url}')`;
        this.style.backgroundSize = "contain";
        this.style.backgroundRepeat = "no-repeat";
        this.style.position = "absolute";
        this.style.height = "100%";
        this.style.width = "100%"
      }.bind(this);
      xhr.send(null);
    };
}
document.registerElement('xkcd-img',XKCD);

See it in action:

Well, this is just the start, let's hope to see this grow better and faster...untill then happy hacking! :)

Descriptor Decorator in Python

| Comments

Decorators and Descriptor are two independent features of Python programming language, but they gel together very well, below is a descriptor decorator ;)

Say, we have a simple Greet class:

1
2
3
4
class Greet():
    msg = "meow"
    def yo(self):
        return "Yo!"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> Greet()
<__main__.Greet object at 0x10046ea90>

>>> greetThem = Greet()

>>> greetThem.yo
<bound method Greet.yo of <__main__.Greet object at 0x10046eb50>>

>>> greetThem.msg
"meow"

>>> greetThem.yo()
"Yo!"

>>> Greet.msg
"meow"

Nothing special so far, everything is as expected...

Now, let's add some magic, first lets create an Accessor descriptor:

1
2
3
4
5
6
7
8
class Accessor(object):
    def __init__(self, fget):
        self.fget = fget

    def __get__(self, obj, type):
        if obj is None:
            return self
        return self.fget(obj)

Now that we have a descriptor, let's decorate our Greet class with it.

1
2
3
4
5
class Greet():
    msg = "meow"
    @Accessor
    def yo(self):
        return "Yo!"
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> Greet()
<__main__.Greet object at 0x10056eb50>

>>> greetThem = Greet()

>>> greetThem.yo
"Yo!"

>>> greetThem.msg
"meow"

>>> Greet.msg
"meow"

Notice greetThem.yo vs greetThem.yo() :)

So what was the trick behind the magic?:

Dotted access to look up a member will result in:

  • Look up for the member in the instance dictionary.

  • If it's not found, the look up happens in the class dictionary.

  • If found it in the class dictionary and it has a descriptor protocol implemented, instead of just returning it, Python executes it!

Clearly the much more concise term of art should be Desecrator, says coriolinus on reddit.

ES6 Array Methods

| Comments

Arrays with the help of ES6 now have uber kool methods in them! Let's have a look at them with few simple examples to understand them.

Array:

  • from()

  • of()

Array.prototype:

  • copyWithin()

  • fill()

  • find()

  • findIndex()

  • keys()

  • entries()

  • values()


Array.from():

Coverts arrayLike and interator objects to arrays.

Simple senario in ES5 to enumarate over a NodeList:

1
2
3
4
var divs = document.querySelectorAll('div');
[].forEach.call(divs, function(node) {
  console.log(node);
});

Same with ES6:

1
2
3
4
var divs = document.querySelectorAll('div');
Array.from(divs).forEach(function(node) {
  console.log(node);
});

Also:

1
2
> Array.from({ 0: 'X', 1: 'Y', length: 2 })
> ['X', 'Y']

Array.of():

This creates a new Array instance with a variable number of arguments, regardless of the type.

1
2
> Array.of(0,true, undefined, null);
> [ 0, true, undefined, null ]

A simple implementation of the same in ES5 would be:

1
2
3
Array.of = function() {
    return Array.prototype.slice.call(arguments);
};

Array.copyWithin():

Given the target starting index, source start and end indices, this method copies the sequence of array elements.

If the starting or the ending indices are negitive values, then the array length is added to them.

1
2
3
4
5
6
7
8
> [1, 3, 5, 7, 9].copyWithin(0, 3);
> [ 7, 9, 5, 7, 9 ]

> [1, 3, 5, 7, 9].copyWithin(0, 1, 3);
> [ 3, 3, 5, 7, 9 ]

> [1, 3, 5, 7, 9].copyWithin(0, -2, -1);
> [ 7, 3, 5, 7, 9 ]

Array.fill():

Fills all the elements of an array from a start index to an end index with a static value.

1
2
3
4
5
6
7
8
> [1,1,2,3,5,8].fill(4)
> [ 4, 4, 4, 4, 4, 4 ]

> [1,1,2,3,5,8].fill(4, 3)
> [ 1, 1, 2, 4, 4, 4 ]

> [1,1,2,3,5,8].fill(4, 1, 3)
> [ 1, 4, 4, 3, 5, 8 ]

Array.find():

This returns a value in the array or undefined, based on the testing function that is passed to this method.

1
isEven = (element, index, array) => (element % 2 === 0)
1
2
3
4
5
> [1,2,3,5,7].find(isEven)
> 2

> [1,3,5,7,9].find(isEven)
> undefined

Array.findIndex():

Similar to find() but retruns the matching index if found, or else returns -1

1
2
3
4
5
> [0,1,3,5,7].findIndex(isEven)
> 0

> [1,3,5,7].findIndex(isEven)
> -1

Array.{keys, entries, values}():

keys, entires and values methods returns a new Array Iterator object that contains keys, values and key/value pairs respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
> alphas = ['R', 'G', 'B']

> keyIter = alphas.keys()

> KeyIter.next()
> { value: 0, done: false }

> KeyIter.next()
> { value: 1, done: false }

> KeyIter.next()
> { value: 2, done: false }

> KeyIter.next()
> { value: undefined, done: true }


> entrIter = alphas.entires()
> entrIter.next().value
> [0, 'R'] // So...on

> valIter = alphas.values();
> valIter.next().value
> 'R' // So...on

Bonus for scrolling till the end ;)

ES7 will have Array.contains as a matter of fact it's already there in FF35+

1
2
3
> [1,2,3,4,5].contains(5) // true

> [0,1,2,3,4].contains(5) // false

Hope this helped, happy hacking! :)

Update 0 After publishing this post noticed one more uber kool post by Dr. Axel Rauschmayer don't miss it!

Date Shifting in Ruby

| Comments

Ruby is a langauge that had many hidden gems, one such is using the << shift operator on Date objects!

Consider the following scenarii:

  • We get the current date.

  • We need to day of previous or the next month for the same date.

1
2
3
4
5
6
7
8
9
10
11
12
13
require 'date'

today = Date.today
# => #<Date: 2014-09-14 ((2456915j,0s,0n),+0s,2299161j)> 

today.strftime('%A')
# => "Sunday"

today.strftime('%B')
# => "September" 

today.strftime('%Y')
# => 2014

Now let's do the shifting:

1
2
3
4
5
6
7
8
9
10
11
last_month = today << 1
# => #<Date: 2014-08-14 ((2456884j,0s,0n),+0s,2299161j)> 

last_month.strftime('%A')
# => "Thursday" 

last_month.strftime('%B')
# => "August" 

last_month.strftime('%Y')
# => "2014" 
1
2
3
4
5
next_month = today >> 2
# => #<Date: 2014-11-14 ((2456976j,0s,0n),+0s,2299161j)> 

next_month.strftime('%A-%B-%Y')
# => "Friday-November-2014" 

We could also shift on the new date:

1
2
Date.new(1988, 02, 01) >> 1
# => #<Date: 1988-03-01 ((2447222j,0s,0n),+0s,2299161j)> 

That's all for now, happy hacking! :)

thisArg in Javascript

| Comments

The other day I was hanging out at #javascript and noticed not many were aware of thisArg that few of the built-ins have in their signature.

Basically if a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn or predicate.If it is not provided, undefined is used instead.

It's improtant to note that if callbackfn is an (Fat) Arrow Function, this was lexically bound when the function was created so thisArg will have no effect.

Ofcourse there are apply, bind and call which could be used to change the execution context taken in thisArg, below is the list of few more built-ins that have thisArg in their signature:

  • Array.from ( arrayLike [ , mapfn [ , thisArg ] ] )

  • Array.prototype.every ( callbackfn [ , thisArg] )

  • Array.prototype.filter ( callbackfn [ , thisArg ] )

  • Array.prototype.find ( predicate [ , thisArg ] )

  • Array.prototype.findIndex ( predicate [ , thisArg ] )

  • Array.prototype.forEach ( callbackfn [ , thisArg ] )

  • Array.prototype.map ( callbackfn [ , thisArg ] )

  • Array.prototype.some ( callbackfn [ , thisArg ] )

Let us see an example of forEach:

1
2
3
4
5
let jedi = {
  name: 'yoda',
  height: '66cms',
  mass: '17 kgs'
};

Without thisArg:

1
2
3
4
5
Object.keys( jedi ).forEach(function( key ) {

  console.log( jedi[ key ] );

});

With thisArg:

1
2
3
4
5
6
7
Object.keys( jedi ).forEach(function( key ) {

  // |this| now refers to `jedi`

  console.log( this[ key ] );

}, jedi ); // last arg is `thisArg`

The same could be achived with bind, but it would be slower.

1
2
3
4
5
6
7
Object.keys( jedi ).forEach(function( key ) {

  // |this| now refers to `jedi`

  console.log( this[ key ] );

}.bind(jedi) ); // We are binding the execution context.

Have a looks at the perf values.

All of them results in the same output, it's advised to use thisArgwhenever possible.

UPDATE: Here a video from webucator explaining the same.

Immediately-invoked Generator Function Expression (IIGFE)

| Comments

You would have heard of IIFEs, here is a intresting pattern I derived when playing with ES6 generators, call it Immediately-invoked generator function expression: IIGFE

1
2
3
4
5
6
7
pow = (function *() {
  return Math.pow((yield "x"), (yield "y"));
}());

pow.next(); // Object { value: "x", done: false }
pow.next(2); //Object { value: "y", done: false }
pow.next(3); //Object { value: 8, done: true }

Update 0:

Found a similar dicussion here

Check for Root User.

| Comments

If we check out the GNU/Linux source code, it's clear that the UID for user with root privilages is set to 0

It's important to note that superuser account always have UID/GID set to 0/0 as we noted from the above links to the source, but the superuser account name need not be root always. [root -> uid 0, but uid -> 0 need not be root.]

So the basic idea of checking if the user is root aka a user with super privilages is to check for the UID/GID.

Let's have a look at how the same is done in few langauges of my choice ;):

In bash:

1
  isRoot=$(($UID == 0))

In nodejs:

1
var isRoot = process.getuid && process.getuid() === 0;

In ruby:

1
isRoot = Process.uid.zero?

In python:

1
2
import os
isRoot = os.geteuid() == 0

In perl:

1
$isRoot = $< == 0;

In haskell:

1
2
import System.Posix.User
let isRoot = fmap (== 0) getRealUserID

In all of the above isRoot will hold a boolean value true if the user is has root privilages or else false.

Hope this was informative! ;)

The other school thought

There are other set of people who prefer to do a try and check method i.e try to some specific root privilage action and check if it succeeded.

There might be many such operations to check, lets stick to a simple example of checking if / is writable?

Let's see how would that look:

Bash:

1
[[ -w / ]] && isRoot=true || isRoot=false

node:

1
2
3
4
5
6
try {
  fs.openSync("/usr/bin/ls","w"); // Workaround.
  isRoot=true;
} catch(e) {
  isRoot=false;
}

ruby:

1
2
3
#is writable by the real user id of this process.?

isRoot = File.writable_real?("/")

python:

1
2
import os
isRoot = os.access('/', os.W_OK)

perl:

1
$isRoot = (-w "/" ? true: false);

haskell:

1
2
3
4
import System.Directory
getPermissions "/"

let isRoot = writeable it

Thunks in Haskell

| Comments

Let's take a simple example of a fib function as an example and try to understand thunks in haskell!

fib function implements Fibonacci seq.

1
2
3
4
haskell-rascal> let fib = 0 : 1 : zipWith (+) fib (tail fib)

haskell-rascal> take 10 fib
[0,1,1,2,3,5,8,13,21,34]

In most of the programming langauges that supports tuples, saying (4+2,7) would be stored as (6,7) but in Haskell it gets stored as (_,7) where the _ is the thunk value.

Lets explore the same in ghci:

1
2
3
4
haskell-rascal> let x = (4+2,7)

haskell-rascal> :print x
x = ((_t1::Integer),7)

Notice that _t1 is the thunk value here, now if we fetch the second element of that tuple, it will be 7, but the first element we not be evaluated yet!

1
2
3
4
5
haskell-racal> snd x
7

haskell-racal> :print x
x = ((_t2::Integer),7)

But as soon as we fetch the first or just evaluate x, the first value will be evaluated.

1
2
3
4
5
haskell-racal> fst x
6

haskell-racal> x
(6,7)

So, a thunk is basically a value that has not yet been computed yet. As per the need it can evaluate or partly-evaluated to a real value. Partial evaluation of a thunk will resulting in a value with more thunks in it.

Now the above function can be expanded as:

1
2
3
fibs                        = 0 : 1 : <thunk>
tail fib                    = 1 : <thunk>
zipWith (+) fib (tail fib)  = <thunk>

The first row left shifted is the second row and the third row is the sum of the first and the second rows and all of them are sharing the same thunk.

take 2 fibs will give use [0, 1] which is direct and does not need further evaluation.

Now if we say take 3 fib Haskell will directly get the 0 and 1, and then it will have to partly evaluate the thunk, so that it can fully evaluate zipWith (+) fib (tail fib), by getting the sum of the first two rows but it can't fully do that, it can begin to sum the first two rows:

1
2
3
fibs                         = 0 : 1 : 1: <thunk>
tail fibs                    = 1 : 1 : <thunk>
zipWith (+) fibs (tail fibs) = 1 : <thunk>

Likewise it keeps on going creating <thunk's> and eval them as and when the need arrives.

If you say fib n and then fib n-m where m<=n the expresion will not be re-evaled but will just take the first n-m numbers from the list it has already evaled!

P.S: This post is a part from my repo haskell-rascal.

navigator.sendBeacon

| Comments

Analytics and diagnostics code are very useful, but they always result in an extra time. To make things easier the Beacon API comes to our rescue!

As The Browser normally ignores asynchronous XMLHttpRequests made in an unload handler and a event on an unload or beforeunload handler is used to post such data to the server.

So, as a work around one would use:

  • Use synchronous XMLHttpRequest.

  • Delay the unload, using image element and setting its src attribute within the unload handler.

  • Create a no-op loop for several seconds within the unload handler.

All the above workarounds are indeed poor coding patterns.

The Beacon specification defines an interface that web developers can use to asynchronously transfer small HTTP data from the User Agent to a web server.

1
2
3
partial interface Navigator {
    boolean sendBeacon(DOMString url, optional (ArrayBufferView or Blob or DOMString or FormData)? data = null);
};

Parameters for the API :

  1. a URL to which the data must be posted.

  2. Optional data which can ArrayBufferView, Blob, DOMString, or FormData data that is to be transmitted.

And it the retruns true on success or else false.

So basically, something like:

1
2
3
4
5
6
7
8
window.addEventListener('unload', logData, false);

function logData() {
    var client = new XMLHttpRequest();
    client.open("POST", "/log", false); // third parameter indicates sync xhr
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(analyticsData);
}

Could be written as:

1
2
3
4
5
window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}

GIF FTW!:

beacon.gif

Refferences:

What are people saying about this?

navigator.sendBeacon It's like UDP over TCP but for webpages. -- @FakeAlexRussell

A 'fire-and-forget' XMLHttpRequest replacement for faster page unloads (& next page loads) -- @richtibbett