Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Challenge

Write a function of type String -> Integer. The input may or may not be a valid JSON string. If it is valid, the resulting JavaScript value is expected to be an object, but may not be. If it is an object, it is expected to have a foo property whose value is expected to be an object, but may not be. This value is expected to have a bar property which is expected to be an object with a baz property whose value is expected to be an array of strings. Each of these strings is expected to be a hex representation of an integer (e.g. 0xFF). If every element of the array meets this expectation, the function should return the sum of all the integers. Otherwise, the function should return NaN. If any of the function's other expectations is not met, the function should return NaN.

Here's a naive solution which only satisfies the "happy" path:

//    f :: String -> Integer
const f = s =>
  JSON.parse(s).foo.bar.baz.reduce((n, s) => n + parseInt(s, 16), 0);

f('{"foo":{"bar":{"baz":["0x0D","0x0E","0x0F"]}}}');  // => 42

Here are some unhappy paths which should produce NaN:

f('[');
f('null');
f('{}');
f('{"foo":{}}');
f('{"foo":{"bar":{}}}');
f('{"foo":{"bar":{"baz":null}}}');
f('{"foo":{"bar":{"baz":[1,2,3]}}}');
f('{"foo":{"bar":{"baz":["foo","bar","baz"]}}}');
f('{"foo":{"bar":{"baz":["0x0D","0x0E","0x0F",null]}}}');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment