Last active
July 15, 2019 00:45
-
-
Save nickytonline/8b24726e9865d61fbde6f93e4d4392bd to your computer and use it in GitHub Desktop.
Having fun recreating some lodash functionality and polyfills
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
// Just having fun creating some polyfills. | |
/** | |
* A polyfill for Object.prototype.entries. | |
* | |
* @returns {[string, any][]} An array of tuples where each tuple is a key/value pair. | |
*/ | |
Object.prototype.entries = Object.prototype.entries || function() { | |
const obj = this; | |
return Object.keys(obj).filter(obj.hasOwnProperty).map(key => [key, obj[key]]); | |
} | |
/** | |
* A polyfill for Object.prototype.fromEntries. | |
* | |
* @param {[string, any][]} An array of tuples where each tuple is a key/value pair. | |
* | |
* @returns {object} An object built from entries. | |
*/ | |
Object.prototype.fromEntries = Object.prototype.fromEntries || function (entries) { | |
return entries.reduce((prev, [key, value]) => { | |
prev[key] = value; | |
return prev; | |
}, {}) | |
} |
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
/** | |
* Returns a new object with the omitted properties specified. | |
* | |
* @param {object} obj The object to omit properties from | |
* @param {string[]} propertiesToOmit The list of properties to omit. | |
* | |
* @returns {object} A new object with the omitted properties. | |
*/ | |
function omit(obj, propertiesToOmit = []) { | |
if (obj == null || !propertiesToOmit.length) { | |
return obj; | |
} | |
const filteredEntries = Object.entries(obj).filter(([key, value]) => !propertiesToOmit.includes(key)); | |
return Object.fromEntries(filteredEntries);; | |
} |
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
/** | |
* Returns a new object with only the specified properties. | |
* | |
* @param {object} obj | |
* @param {string[]} propertiesToPick | |
* | |
* @returns {object} A new object with only the specified properties. | |
*/ | |
function pick(obj, propertiesToPick = []) { | |
if (obj == null || !propertiesToPick.length) { | |
return obj; | |
} | |
const filteredEntries = Object.entries(obj).filter(([key, value]) => propertiesToPick.includes(key)); | |
return Object.fromEntries(filteredEntries);; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment