Creating a setter function in JavaScript Objects

As part of one of my projects I have had a central object called "layout" with it being to do with manipulating SVGs, and as part of that I decided it would be easier to write said layout object such that it has a getter and setter function, so that:

layout.item.points.X = 20;

…becomes:

layout.set('item.points.X',20);

…much more verbose and much more functional, I’m sure you’ll agree!

So first, the getter function, well, this couldn’t be easier really:

const layout = {
  get: function() {
    return this;
  },
  set: // To be confirmed
  /* All other properties */
}

But now, what about the setter? Well, that’s where it gets a bit more complicated. First, we need to take the propChain and newState from the user:

const layout = {
  set: function(propChain,newState) {}
}

I have written it so that it follows the usual object notation, as per the example above, so if you want to set item’s pointX value to 20 you give it layout.set('item.points.X',20).

First of all, let’s prevent the user from being able to change either the setter or getter:

const layout = {
  set: function(propChain,newState) {
    if (['get','set'].includes(propChain)) {
      console.warn(`🛑 What are you doing? Should you really be changing either of these functions? `);
      return;
    }
  }
}

And get our function to exit if the propChain is empty:

const layout = {
  set: function(propChain,newState) {
    if (['get','set'].includes(propChain)) {
      console.warn(`🛑 What are you doing? Should you really be changing either of these functions? `);
      return;
    }
    if (!propChain) return;
  }
}

Now for the fun bit! We want to split our propChain into sections and:

  • Check for the first property on our original object, and create it if it isn’t there
  • If it is there (which it now is) check if we’re at the end of the provided chain
  • If we are, set the property to equal the given newState
  • If not, go one level further into the object (having just created the new property) and repeat from step 1
const layout = {
  set: function(propChain,newState) {
    if (['get','set'].includes(propChain)) {
      console.warn(`🛑 What are you doing? Should you really be changing either of these functions? `);
      return;
    }
    if (!propChain) return;
    propChain.split('.').reduce((original/*Object*/,prop,level/*how deep we are into the chain*/) => {},this);
  }
}

So, um, what?

Let’s go through it bit-by-bit.

We use the split function to split propChain from a string into an array, using . as the breaking point (just how you’d access an object property in JavaScript anyway) on which we can now use the reduce function.

The reduce function is immensely powerful and I’m often guilty of discarding it in favour of map because I’m more comfortable there.

The reduce function takes up to 4 parameters (read more on MDN) but we’re only interested in the first 3: the accumulated value, the current value and the current index, which we’re calling original, prop and level.

const layout = {
  set: function(propChain,newState) {
    if (['get','set'].includes(propChain)) {
      console.warn(`🛑 What are you doing? Should you really be changing either of these functions? `);
      return;
    }
    if (!propChain) return;
    propChain.split('.').reduce((original,prop,level) => {
      // Firstly, check if our original object has the property, and add it if not.
      if (!(prop in original)) {
        original[prop] = {}; // Why a blank object? In case we go deeper into the chain and need to add properties to this, which you can't on undefined, 0 or an empty string
      }
    },this);
  }
}

Could I not have used original.hasOwnProperty(prop)? In JavaScript yes but in TypeScript the linter shouts at you: Do not access Object.prototype method 'hasOwnProperty' from target object no-prototype-builtins.

const layout = {
  set: function(propChain,newState) {
    if (['get','set'].includes(propChain)) {
      console.warn(`🛑 What are you doing? Should you really be changing either of these functions? `);
      return;
    }
    if (!propChain) return;
    propChain.split('.').reduce((original,prop,level) => {
      if (!(prop in original)) {
        original[prop] = {};
      }
      // Now check if we're at the end of our given chain and if we are, set the property to the given newState
      if (level === propChain.split('.').length - 1 /*Remember, indexing starts at 0*/) {
        original[prop] = newState;
      }
      // Now return our object, and that's it!
      return original[prop];
    },this);
  }
}

Finally we arrive at:

const layout = {
  get: function() {
    return this;
  },
  set: function(propChain,newState) {
    if (['get','set'].includes(propChain)) {
      console.warn(`🛑 What are you doing? Should you really be changing either of these functions? `);
      return;
    }
    if (!propChain) return;
    propChain.split('.').reduce((original,prop,level) => {
      if (!(prop in original)) {
        original[prop] = {};
      }
      if (level === propChain.split('.').length - 1) {
        original[prop] = newState;
      }
      return original[prop];
    },this);
  }
}

Or, in TypeScript:

interface LayoutObject extends Record<string, unknown> {
  get: () => LayoutObject;
  set: (
    propChain: string,
    newState: Record<string, unknown> | string | number
  ) => void;
  // All the rest of our properties
}

// TypeScript uses interfaces to define, well, almost everything!

const layout: LayoutObject = {
  get: function (): LayoutObject {
    return this;
  },
  set: function (
    propChain: string,
    newState: Record<string, unknown> | string | number
  ): void {
    if (['get', 'set'].includes(propChain)) {
      console.warn(
        `🛑 What are you doing? Should you really be changing either of these functions?`
      );
      return;
    }
    if (!propChain) return;
    propChain.split('.').reduce((original, prop, level) => {
      if (!(prop in original)) {
        original[prop] = {};
      }
      if (level === propChain.split('.').length - 1) {
        original[prop] = newState;
      }
      return original[prop];
    }, this);
  },
  // All the rest of the properties
}

Solving the Project Euler Problems – Problem 6

The sum of the squares of the first ten natural numbers is, 12 + 22 + … + 102 = 385.

The square of the sum of the first ten natural numbers is, (1 + 2 + … + 10)2 = 552 = 3025.

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

No gists found

This one oddly seems relatively simple. simply take a number, work out the sum of 1 to that number then square it, work out the sum of the squares of 1 to that number and find the difference between your 2 results. Job done!

Solving the Project Euler Problems – Problem 2

The main consideration here was how to calculate the Fibonacci sequence without taking up too many resources, a common danger with recursive functions which are often touted as the solution for working out the sequence and other things like factorials. It turns out the Fibonacci sequence as a recursive function is fine up until about the 10th term, but any further than that? Not advisable!

No gists found

The much quicker solution that I’ve found is to do it as an array, which takes simple values for its calculations rather than calling a recursive function again and again and again.

The second performance optimisation is checking whether our Fibonacci number is even, which when doing it a limited number of times, is fine to do just by checking if n modulo 2 is 0, but how many times will we be doing this? Off the top of your head which Fibonacci term is the largest below 4,000,000? The 10th? The 50th? The 1,000th? We don’t know how many until we actually do it. As it happens it’s the 32nd term, 3,524,578. Run that recursive function 32 times!

As division is slow and all we’re using it to do is check if a number is even, is there a better way? Well kind of, we can check if it isn’t odd. This is done by using the bitwise AND operator. This takes the binary representation of a number – 2019’s would be 11111100011 – and it’s that final bit we’re interested in, if it’s 1 then the number is odd and if it’s 0 it’s even. So using the bitwise AND operator to compare any number to 1 checks only 2 bits and avoids division.

Solving the Project Euler Problems – Problem 1

After stumbling across an article on Medium by Bennett Garner, I discovered the Project Euler problems and that it would be a good idea to showcase my skills in solving them in a variety of ways, as a good starting point to get a code portfolio going, so here goes with – as natural a starting point as any – problem 1!

All of the Project Euler Problems can be found at ProjectEuler.net.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

No gists found

There were 2 ways I considered to tackle this:

  • Loop from 1 to 1000 (or as in the code, n) and check each number for dividing by 3 and 5 respectively, adding them to the result if either is true
  • Reduce the number of loops by 47% and run our loop n/3 + n/5 times (for those interested, 1/3 + 1/5 = 8/15, so this reduction percentage works for any integer), by dividing n by 3, running that loop, adding 3 times each number to the result – which takes division out of the loop as well – then doing the same again, only now having to check (on a smaller loop) if our result was already added as being a multiple of 3.