diff --git a/README.md b/README.md index c5ab3f8ba..dfda72618 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ * [`initializeArrayWithValues`](#initializearraywithvalues) * [`intersection`](#intersection) * [`last`](#last) +* [`mapObject`](#mapobject) * [`nthElement`](#nthelement) * [`pick`](#pick) * [`pull`](#pull) @@ -47,7 +48,7 @@ ### Browser * [`bottomVisible`](#bottomvisible) -* [`current-URL`](#current-url) +* [`currentURL`](#currenturl) * [`elementIsVisibleInViewport`](#elementisvisibleinviewport) * [`getScrollPosition`](#getscrollposition) * [`getURLParameters`](#geturlparameters) @@ -191,7 +192,7 @@ const compact = (arr) => arr.filter(Boolean); ### countOccurrences -Counts the occurences of a value in an array. +Counts the occurrences of a value in an array. Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array. @@ -362,7 +363,7 @@ const initial = arr => arr.slice(0, -1); ### initializeArrayWithRange -Initialized an array containing the numbers in the specified range. +Initializes an array containing the numbers in the specified range. Use `Array(end-start)` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. You can omit `start` to use a default value of `0`. @@ -415,6 +416,23 @@ const last = arr => arr[arr.length - 1]; [⬆ back to top](#table-of-contents) +### mapObject + +Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value. + +Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to stor the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations). + +```js +const mapObject = (arr, fn) => + (a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( ); +/* +const squareIt = arr => mapObject(arr, a => a*a) +squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 } +*/ +``` + +[⬆ back to top](#table-of-contents) + ### nthElement Returns the nth element of an array. @@ -554,7 +572,7 @@ const tail = arr => arr.length > 1 ? arr.slice(1) : arr; ### take -Returns an array with n elements removed from the beggining. +Returns an array with n elements removed from the beginning. Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning. @@ -1280,7 +1298,7 @@ Returns an array of lines from the specified file. Use `readFileSync` function in `fs` node package to create a `Buffer` from a file. convert buffer to string using `toString(encoding)` function. -creating an array from contents of file by `split`ing file content line by line(each `\n`). +creating an array from contents of file by `split`ing file content line by line (each `\n`). ```js const fs = require('fs'); @@ -1304,7 +1322,7 @@ const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').spl Removes any properties except the ones specified from a JSON object. Use `Object.keys()` method to loop over given json object and deleting keys that are not `include`d in given array. -also if you give it a special key(`childIndicator`) it will search deeply inside it to apply function to inner objects too. +Also if you give it a special key (`childIndicator`) it will search deeply inside it to apply function to inner objects too. ```js const cleanObj = (obj, keysToKeep = [], childIndicator) => { @@ -1394,7 +1412,7 @@ const anagrams = str => { Capitalizes the first letter of a string. Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again. -Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lower case. +Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase. ```js const capitalize = ([first,...rest], lowerRest = false) => @@ -1436,7 +1454,7 @@ const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); Converts a string from camelcase. Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase. -Omit the scond argument to use a default separator of `_`. +Omit the second argument to use a default separator of `_`. ```js const fromCamelCase = (str, separator = '_') => @@ -1529,7 +1547,7 @@ const extendHex = shortHex => Returns the native type of a value. -Returns lower-cased constructor name of value, "undefined" or "null" if value is undefined or null +Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null ```js const getType = v => diff --git a/docs/index.html b/docs/index.html index 2383f3c8c..a951ded74 100644 --- a/docs/index.html +++ b/docs/index.html @@ -53,6 +53,7 @@ initializeArrayWithValues intersection last +mapObject nthElement pick pull @@ -70,7 +71,7 @@

Browser

bottomVisible -current-URL +currentURL elementIsVisibleInViewport getScrollPosition getURLParameters @@ -184,7 +185,7 @@ If the original array can't be split evenly, the final chunk will contain the re // compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]

countOccurrences

-

Counts the occurences of a value in an array.

+

Counts the occurrences of a value in an array.

Use Array.reduce() to increment a counter each time you encounter the specific value inside the array.

const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
 // countOccurrences([1,1,2,1,2,3], 1) -> 3
@@ -271,7 +272,7 @@ Use Array.reduce() to create an object, where the keys are produced
 // initial([1,2,3]) -> [1,2]
 

initializeArrayWithRange

-

Initialized an array containing the numbers in the specified range.

+

Initializes an array containing the numbers in the specified range.

Use Array(end-start) to create an array of the desired length, Array.map() to fill with the desired values in a range. You can omit start to use a default value of 0.

const initializeArrayWithRange = (end, start = 0) =>
@@ -297,6 +298,16 @@ You can omit value to use a default value of 0.

const last = arr => arr[arr.length - 1];
 // last([1,2,3]) -> 3
 
+

mapObject

+

Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.

+

Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new Array to stor the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).

+
const mapObject = (arr, fn) => 
+  (a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( );
+/*
+const squareIt = arr => mapObject(arr, a => a*a)
+squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 }
+*/
+

nthElement

Returns the nth element of an array.

Use Array.slice() to get an array containing the nth element at the first place. @@ -372,7 +383,7 @@ This method also works with strings.

// tail([1]) -> [1]

take

-

Returns an array with n elements removed from the beggining.

+

Returns an array with n elements removed from the beginning.

Use Array.slice() to create a slice of the array with n elements taken from the beginning.

const take = (arr, n = 1) => arr.slice(0, n);
 // take([1, 2, 3], 5) -> [1, 2, 3]
@@ -419,7 +430,7 @@ If lengths of the argument-arrays vary, undefined is used where no
   document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
 // bottomVisible() -> true
 
-

currentURL

+

currentURL

Returns the current URL.

Use window.location.href to get current URL.

const currentURL = () => window.location.href;
@@ -780,7 +791,7 @@ const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.s
 

Returns an array of lines from the specified file.

Use readFileSync function in fs node package to create a Buffer from a file. convert buffer to string using toString(encoding) function. -creating an array from contents of file by spliting file content line by line(each \n).

+creating an array from contents of file by spliting file content line by line (each \n).

const fs = require('fs');
 const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').split('\n');
 /*
@@ -797,7 +808,7 @@ console.log(arr) // -> ['line1', 'line2', 'line3']
 

cleanObj

Removes any properties except the ones specified from a JSON object.

Use Object.keys() method to loop over given json object and deleting keys that are not included in given array. -also if you give it a special key(childIndicator) it will search deeply inside it to apply function to inner objects too.

+Also if you give it a special key (childIndicator) it will search deeply inside it to apply function to inner objects too.

const cleanObj = (obj, keysToKeep = [], childIndicator) => {
   Object.keys(obj).forEach(key => {
     if (key === childIndicator) {
@@ -852,7 +863,7 @@ Base cases are for string length equal to 2 or 1
 

Capitalize

Capitalizes the first letter of a string.

Use destructuring and toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.join('') to make it a string again. -Omit the lowerRest parameter to keep the rest of the string intact, or set it to true to convert to lower case.

+Omit the lowerRest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

const capitalize = ([first,...rest], lowerRest = false) =>
   first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
 // capitalize('myName') -> 'MyName'
@@ -873,7 +884,7 @@ Omit the lowerRest parameter to keep the rest of the string intact,
 

fromCamelCase

Converts a string from camelcase.

Use replace() to remove underscores, hyphens and spaces and convert words to camelcase. -Omit the scond argument to use a default separator of _.

+Omit the second argument to use a default separator of _.

const fromCamelCase = (str, separator = '_') =>
   str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
     .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase();
@@ -925,7 +936,7 @@ Return the string truncated to the desired length, with ... appende
 

getType

Returns the native type of a value.

-

Returns lower-cased constructor name of value, "undefined" or "null" if value is undefined or null

+

Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null

const getType = v =>
   v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
 // getType(new Set([1,2,3])) -> "set"
diff --git a/tag_database b/tag_database
index 3d17b3376..562b3b388 100644
--- a/tag_database
+++ b/tag_database
@@ -13,7 +13,7 @@ collatz:math
 compact:array
 compose:function
 countOccurrences:array
-current-URL:browser
+currentURL:browser
 curry:function
 deepFlatten:array
 difference:array
@@ -57,6 +57,7 @@ JSONToDate:date
 JSONToFile:node
 last:array
 lcm:math
+mapObject:array
 median:math
 nthElement:array
 objectFromPairs:object