How Identity Functions Are Useful In JavaScript
All identity functions do is return the first argument given to them:
var identity = function(arg1) { return arg1; };
This doesn't sound too useful, but it actually can simplify code quite a bit. Firstly, here is a simple inheritance structure of two objects. One that defines base API methods and one that represents one API location:
var BaseAPI = function() { var self = {}; self.baseUrl = '/test/:location'; self.getUrl = null;// Set by child self.send = function(callback) { var url = this.baseUrl; if (typeof this.getUrl === 'function') { url = this.getUrl(url); } // Simulate API call by making the code asynchronous. setTimeout(function() { callback('Called with ' + url) }, 200); }; return self; }; var CarApi = function() { var self = Object.create(BaseAPI()); self.getUrl = function(url) { return url.replace(':location', 'cars'); } return self; }; var api = CarApi(); api.send(function(resultMessage) { console.log(resultMessage);// Called with /test/cars });
All the child has to do is change the URL by overriding a function to define custom behavior. But for each function customization that the BaseApi will need to support, a new if check needs to be added. If instead the getUrl starts as an identity function, the send call in BaseApi can be simplified:
var BaseAPI = function() { var self = {}; self.baseUrl = '/test/:location'; self.getUrl = identity; self.send = function(callback) { var url = this.getUrl(this.baseUrl); // Simulate API call by making the code asynchronous. setTimeout(function() { callback('Called with ' + url) }, 200); }; return self; };
So when code is written as a set of one argument Pure Functions, behavior customization can be simplified. Identity functions are available in many libraries like Lodash.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/identity.js














