Big Data/Analytics Zone is brought to you in partnership with:

Gary Sieling is a software developer interested in dev-ops, database technologies, and machine learning. He has a computer science degree from the Rochester Institute of Technology. He has worked on many products in the legal and regulatory industries, having worked on and supported several data warehousing applications. Gary is a DZone MVB and is not an employee of DZone and has posted 62 posts at DZone. You can read more from them at their website. View Full User Profile

Self-Modifying Javascript Objects

07.19.2013
| 4275 views |
  • submit to reddit

I thought it’d be interesting to consider Javascript objects which can modify their own behavior over time. A use case for this (what I’m doing) is pages of data, where data is first looked up, then cached in memory, then cleared. A simple case (demonstrated below) is memoization.

The following query will do an ajax lookup of some data:

function loadData() {
  var data;
 
  $.ajax({
    url: "blocks/" + this.block,
    async: false
  }).done(function(blockData) {
    data = blockData.split("\n")
    for (var i = 0; i < data.length; i++) {
      data[i] = data[i].split("\t")
    }
  });
 
  return data;
}
 
var x = {block: 'xabnh', getData: loadData}
 
x.getData();
Array[2501]

This shows how one might trigger caching the results. Once retrieved, the cached data is hidden within a closure, and the mechanism for retrieving data is updated. In the case of a memory manager, these pages are later cleared out by replacing the memoization function with a third function, which starts the process all over again.

var x = {block: 'xabnh', getData: memoize(loadData)}
 
function memoize(getData) {
  return function() {
    console.log('loading');
    var data = getData.apply(this);
    function savedData() {
      console.log('memoized');
      return data;
    }
    this.getData = savedData;
 
    return data;
  }
}
 
x.getData()
loading
Array[2501]
x.getData()
memoized
Array[2501]

There are a few downsides to this approach; data in the closure is hidden from inspection, the current state of the object is hidden, and can change quickly. A generalized approach to this problem might pass an object into the getData function to show state or trigger a debug mode.

Published at DZone with permission of Gary Sieling, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)