assignTo In JavaScript
A common problem I often encounter is having to create an entire callback function do simple actions like multiple function calls or assigning object properties. While function calls can be handled with tools like partial and over, assigning object properties cannot. Which is why I created an assignTo function. But first here is the code in the standard way:
var apiRequest = function(name, callback) { // Simulate a server call. setTimeout(function() { return callback('car', name === 'mx-5' ? 'roadster' : 'other'); }, 500); }; var updateObject = function(callback) { var car = { name: 'mx-5', type: null, subType: null }; apiRequest(car.name, function(name, type) { car.type = name; car.subType = type; return callback(car); }); }; updateObject(function(car) { console.log(car); // { name: 'mx-5', type: 'car', subType: 'roadster' } withAssignTo(); });
And here is how assignTo simplifies the above:
var updateObject = function(callback) { var car = { name: 'mx-5', type: null, subType: null }; apiRequest(car.name, assignTo(car, 'type', 'subType', callback)); }; updateObject(function(car) { console.log(car); // { name: 'mx-5', type: 'car', subType: 'roadster' } });
Here is assignTo:
var assignTo = function(/* obj, properties..., callback */) { var args = Array.prototype.slice.call(arguments), obj = args[0], properties = args.slice(1, -1), callback = args.slice(-1)[0]; return function() { var innerArgs = Array.prototype.slice.call(arguments); innerArgs.forEach(function(arg, index) { obj[properties[index]] = arg; }); return callback(obj); }; };
The assignTo can also be expanded with at instead of obj[properties[index]] to support a syntax like assignTo(obj, 'a[0].test', callback), but I wanted to keep the implementation simple for demonstration purposes.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/assignTo.js









