The Map Join Pattern (JavaScript)
Normally, interacting with sets of string data requires saving and managing variables. But instead by combining 3 sets of operations; splitting, mapping and joining, that can all be replaced transforming the logic into one flow. For example, the below simulates the retrieval of an element by creating an object with classes. Which is then manipulated only if a class matches a specific condition:
function extendColumnClasses(classes) { return classes.split(' ').map(function(cssClass) { return cssClass.indexOf('col-') > -1 ? cssClass + 'x' : cssClass; }).join(' '); } var htmlEl = { className: 'visible col-sm-4 pull-right' }; htmlEl.className = extendColumnClasses(htmlEl.className); console.log(htmlEl.className); // visible col-sm-4x pull-right
This abstraction can also be applied to file parsing (and has many other applications):
function formatLines(file) { return file.split('\n').map(function(line) { return line[0].toUpperCase() + line.substring(1) + '.'; }).join('\n') } // Using a template literal to simulate the line endings in a normal file easily var file = `line 1 Line 2 line 3`; console.log(formatLines(file)); // Line 1. // Line 2. // Line 3.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/mapJoin.js













