niloy / blog

blog raw files
3 stars 1 forks source link

Things I miss in Javascript #3

Open niloy opened 11 years ago

niloy commented 11 years ago

Things I miss in Javascript

Although I am happy to see JS getting extended and getting cool new features, there are still many things I find missing that are really easy to implement. I mean, its trivial to implement these missing features by JS itself. Anyways, here is the list of stuff I find missing in Javascript in no particular order.

Functional way of looping based on a number

I wish this would work, its easy to implement it though but wish it came out of the box:

(5).times(function(i) {
  console.log(i);
});

Easy functional way to iterate an Object

Why cant I iterate an object using:

  var a = {foo: "bar"};

  a.forEach(function(value, key) {
    console.log(value, key);
  });

Instead, I have to write:

  Object.keys(a).forEach(function(key) {
    console.log(key, a[key]);
  });

Why are ES5 Object functions implemented as static functions?

Take Object.freeze for example, why do I need to write:

  Object.freeze(a);

Why cant I simply write:

  a.freeze();

Sure, I understand objects created using Object.create(null) wont have those functions, but it isnt hard to have both static and non-static versions.

Array group function

I really like the array functions like map, filter, reduce introduced in ES5. But, there is no function which could run over an array and group them in categories. Such a function is really handy when you query a database using a ORDER BY clause and you want to group the result set.

Example, say u have an array with some arbitrary numbers and you want to group them based on even and odd.

  var a = [1, 9, 5, 7, 23, 32, 99, 150];

  var b = a.group(function(n) {
    return (n % 2 === 0) ? "even" : "odd";
  });

  console.log(b);
  // b = {
  //   even: [32, 150],
  //   odd: [1, 9, 5, 7, 23, 99]
  // };

It is simple to implement group function:

  Array.prototype.group = function(groupFunction) {
    var groupedArray = [];

    this.forEach(function(item) {
      var group = groupFunction(item);

      if (!(group in groupedArray)) {
        groupedArray[group] = [];
      }

      groupedArray[group].push(item);
    });

    return groupedArray;
  };

Preventing object property removal