Created
January 10, 2019 01:44
-
-
Save mrboli/a22ce7bfda93010fe96bc5916424229c to your computer and use it in GitHub Desktop.
Map fn for Linked Lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// function Node(data, next = null) { | |
// this.data = data; | |
// this.next = next; | |
// } | |
function map(head, fn) { | |
if (!head) return null; // Just return bad nodes | |
const mappedHead = new Node(fn(head.data)); | |
let lastMappedNode = mappedHead; | |
let currentNode = head.next; | |
let currentMappedNode; | |
while (currentNode) { | |
// Create the new mapped node | |
currentMappedNode = new Node(fn(currentNode.data)); | |
// Link the last node | |
lastMappedNode.next = currentMappedNode; | |
// Update the pointers | |
currentNode = currentNode.next; | |
lastMappedNode = currentMappedNode; | |
} | |
return mappedHead; | |
} | |
// const secondElem = Node('second'); | |
// const head = Node('head', secondElement); | |
// Node.prototype.map = Node.prototype.map || map(this); | |
// map(head, elem => elem + 1); | |
// head.map(elem => elem + 1); | |
// const arr = [1, 2, 3]; | |
// arr.map(elem => { | |
// return elem + 1; | |
// }); | |
// const reduceInputFunction = function (accumulator, currentValue, index, originalArray) { | |
// }; | |
// arr.reduce(reduceInputFunction); | |
// const mapInputFunction = function (arrayElement, index, originalArray) { | |
// return arrayElement + 1; | |
// }; | |
// arr.map(mapInputFunction); | |
// arr.map(function (arrayElement) { | |
// return arrayElement + 1; | |
// }); | |
// arr.map(arrayElem => { | |
// return arrayElement + 1; | |
// }); | |
// arr.map(arrayElem => arrayElement + 1); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment