This is one of those functions that does something obvious, but encourages a better practice by making the operation take much less time. Firstly, here is some JSON parsing code without attempt:
var getHp = function(json) { var data = 'Not Found'; try { data = JSON.parse(json); } catch (e) {} if (data.hp) { return data.hp; } return 'Not Found'; }; console.log(getHp('{ "car": "miata", "hp": 150 }'));// 150 console.log(getHp('{}'));// Not Found console.log(getHp(''));// Not Found console.log(getHp({}));// Not Found
That is a simple approach, but when there is time pressure and so on in projects basic checks like the above tend to be ignored. So the solution is to make them so simple, that they become natural:
var getHp = function(json) { var data = attempt(JSON.parse.bind(this, json)); if (data.hp) { return data.hp; } return "Not Found"; }; console.log(getHp('{ "car": "miata", "hp": 150 }'));// 150 console.log(getHp('{}'));// Not Found console.log(getHp(''));// Not Found console.log(getHp({}));// Not Found
In the above example it is just slightly more code than using JSON.parse on its own. bind is a core JavaScript feature available in all modern browsers. The attempt function just abstracts the try and catch:
var attempt = function(callback) { try { return callback(); } catch (e) { return e; } };
This is available in various utility libaries like Lodash.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/attempt.js