Joined March 2012
·

Bryan Parker

Chicago, IL
·
·

Posted to `isOdd` function in JavaScript over 1 year ago

If you're interested in a signed alternative, consider a simple example using bitwise operators:

function isOdd(num) {
  if (num === 0) return false;

  return (num & -num) === 1;
}

isOdd(-4);   // false
isOdd(-3);  // true
isOdd(0);   // false
isOdd(3);   // true
isOdd(4);   // false
Posted to Transforming JSON over 1 year ago

One might wonder of what use this is. I mean, we've gotten by so far without providing any callbacks, right? One use case that I find myself using the optional callbacks are when a cycle is defined in the JSON object. Consider the following JSON:

let o = {
  k1: 'key1',
  k2: o
};

You'll notice that k2 points back to the original object, o. Some platforms will automatically detect this and eliminate the cyclic key (k2 in this case).

Alternatively, you could provide a callback to stringify to detect said cycle and remove the key yourself:

let seen = [];
JSON.stringify(o, (key, val) => {
  if (val && typeof(val) === 'object') {
    if (seen.includes(val)) {
      return;  // Uh-oh, a cycle
    }

    // Record this value to ensure we avoid serializing it again
    seen.push(val);
  }

  return val;
});

Note: I didn't actually run the code above, so errors may exist.

Achievements
70 Karma
0 Total ProTip Views