diff --git a/README.md b/README.md index ed61b94d0..3917284fe 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,7 @@ average(1, 2, 3); * [`call`](#call) * [`collectInto`](#collectinto) * [`flip`](#flip) +* [`over`](#over) * [`pipeFunctions`](#pipefunctions) * [`promisify`](#promisify) * [`spreadOver`](#spreadover) @@ -472,6 +473,29 @@ Object.assign(b, a); // == b [⬆ Back to top](#table-of-contents) +### over + +Creates a function that invokes each provided function with the arguments it receives and returns the results. + +Use `Array.map()` and `Function.apply()` to apply each function to the given arguments. + +```js +const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); +``` + + +Examples + +```js +const minMax = over(Math.min, Math.max); +minMax(1, 2, 3, 4, 5); // [1,5] +``` + + + +[⬆ Back to top](#table-of-contents) + + ### pipeFunctions Performs left-to-right function composition. diff --git a/docs/index.html b/docs/index.html index a1945a1c7..110f8eb3c 100644 --- a/docs/index.html +++ b/docs/index.html @@ -50,7 +50,7 @@ scrollToTop(); } }, false); - }
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
const call = (key, ...args) => context => context[key](...args); + } 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.Search for snippet...Adaptercall collectInto flip over pipeFunctions promisify spreadOverArraychunk compact countBy countOccurrences deepFlatten difference differenceWith dropElements dropRight everyNth filterNonUnique findLast flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection isSorted join last longestItem mapObject maxN minN nthElement partition pull pullAtIndex pullAtValue reducedFilter remove sample sampleSize shuffle similarity sortedIndex symmetricDifference tail take takeRight union uniqueElements without zip zipObject zipWithBrowserarrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange redirect runAsync scrollToTop setStyle show toggleClass UUIDGeneratorBrowserDateformatDuration getDaysDiffBetweenDates tomorrowFunctionchainAsync compose curry defer functionName memoize negate once runPromisesInSeries sleepMathaverage averageBy clampNumber digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeIntegerNodeatob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNodeObjectdeepClone defaults equals findKey findLastKey forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge objectFromPairs objectToPairs omit omitBy orderBy pick pickBy shallowClone size transform truthCheckCollectionStringanagrams byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isLowerCase isUpperCase mask palindrome pluralize reverseString sortCharactersInString splitLines toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin wordsTypegetType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSONUtilitycastArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toDecimalMark toOrdinalSuffix validateNumber yesNo AdaptercallGiven a key and a set of arguments, call them when given a context. Primarily useful in composition.Use a closure to call a stored key with stored arguments.const call = (key, ...args) => context => context[key](...args); Show examplesPromise.resolve([1, 2, 3]) .then(call('map', x => 2 * x)) .then(console.log); //[ 2, 4, 6 ] @@ -72,6 +72,9 @@ Promise.reso mergePerson(b); // == b b = {}; Object.assign(b, a); // == b +📋 Copy to clipboardoverCreates a function that invokes each provided function with the arguments it receives and returns the results.Use Array.map() and Function.apply() to apply each function to the given arguments.const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); +Show examplesconst minMax = over(Math.min, Math.max); +minMax(1, 2, 3, 4, 5); // [1,5] 📋 Copy to clipboardpipeFunctionsPerforms left-to-right function composition.Use Array.reduce() with the spread operator (...) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); Show examplesconst add5 = x => x + 5; const multiply = (x, y) => x * y; diff --git a/snippets/over.md b/snippets/over.md index ed2a1fedc..31ab12963 100644 --- a/snippets/over.md +++ b/snippets/over.md @@ -10,5 +10,5 @@ const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); ```js const minMax = over(Math.min, Math.max); -minMax(1,2,3,4,5); // [1,5] +minMax(1, 2, 3, 4, 5); // [1,5] ```
const call = (key, ...args) => context => context[key](...args);
Promise.resolve([1, 2, 3]) .then(call('map', x => 2 * x)) .then(console.log); //[ 2, 4, 6 ] @@ -72,6 +72,9 @@ Promise.reso mergePerson(b); // == b b = {}; Object.assign(b, a); // == b +
Creates a function that invokes each provided function with the arguments it receives and returns the results.
Use Array.map() and Function.apply() to apply each function to the given arguments.
Array.map()
Function.apply()
const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); +
const minMax = over(Math.min, Math.max); +minMax(1, 2, 3, 4, 5); // [1,5]
Performs left-to-right function composition.
Use Array.reduce() with the spread operator (...) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
Array.reduce()
...
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
const add5 = x => x + 5; const multiply = (x, y) => x * y; diff --git a/snippets/over.md b/snippets/over.md index ed2a1fedc..31ab12963 100644 --- a/snippets/over.md +++ b/snippets/over.md @@ -10,5 +10,5 @@ const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); ```js const minMax = over(Math.min, Math.max); -minMax(1,2,3,4,5); // [1,5] +minMax(1, 2, 3, 4, 5); // [1,5] ```