Skip to content

Instantly share code, notes, and snippets.

@nickytonline
Last active July 15, 2019 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickytonline/8b24726e9865d61fbde6f93e4d4392bd to your computer and use it in GitHub Desktop.
Save nickytonline/8b24726e9865d61fbde6f93e4d4392bd to your computer and use it in GitHub Desktop.
Having fun recreating some lodash functionality and polyfills
// 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;
}, {})
}
/**
* 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);;
}
/**
* 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