Revert "adds deepMapKeys snippet"

This reverts commit 73470c50d9.
This commit is contained in:
Ilia Aphtsiauri
2018-12-09 18:48:59 +02:00
parent 56e7689a97
commit cc652ac653
7 changed files with 2592 additions and 2647 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

70
package-lock.json generated
View File

@ -5250,6 +5250,48 @@
}
}
},
"jest-tap-reporter": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/jest-tap-reporter/-/jest-tap-reporter-1.9.0.tgz",
"integrity": "sha512-KBNkyWWDO0sGc593H04+QJuMHm9WEwe/0RnMD5ke2spA7nNMQao3ktU34brfOBKk7vNn5EbGIr2pODxNQo+bNA==",
"dev": true,
"requires": {
"@babel/code-frame": "7.0.0-beta.36",
"chalk": "2.4.1",
"string.prototype.padend": "3.0.0",
"string.prototype.padstart": "3.0.0",
"strip-ansi": "4.0.0",
"utf8-bar": "0.1.0"
},
"dependencies": {
"@babel/code-frame": {
"version": "7.0.0-beta.36",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0-beta.36.tgz",
"integrity": "sha512-sW77BFwJ48YvQp3Gzz5xtAUiXuYOL2aMJKDwiaY3OcvdqBFurtYfOpSa4QrNyDxmOGRFSYzUpabU2m9QrlWE7w==",
"dev": true,
"requires": {
"chalk": "2.4.1",
"esutils": "2.0.2",
"js-tokens": "3.0.2"
}
},
"ansi-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
"dev": true
},
"strip-ansi": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
"dev": true,
"requires": {
"ansi-regex": "3.0.0"
}
}
}
},
"jest-util": {
"version": "23.4.0",
"resolved": "https://registry.npmjs.org/jest-util/-/jest-util-23.4.0.tgz",
@ -7901,6 +7943,28 @@
}
}
},
"string.prototype.padend": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/string.prototype.padend/-/string.prototype.padend-3.0.0.tgz",
"integrity": "sha1-86rvfBcZ8XDF6rHDK/eA2W4h8vA=",
"dev": true,
"requires": {
"define-properties": "1.1.2",
"es-abstract": "1.11.0",
"function-bind": "1.1.1"
}
},
"string.prototype.padstart": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/string.prototype.padstart/-/string.prototype.padstart-3.0.0.tgz",
"integrity": "sha1-W8+tOfRkm7LQMSkuGbzwtRDUskI=",
"dev": true,
"requires": {
"define-properties": "1.1.2",
"es-abstract": "1.11.0",
"function-bind": "1.1.1"
}
},
"string_decoder": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz",
@ -8343,6 +8407,12 @@
"integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==",
"dev": true
},
"utf8-bar": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/utf8-bar/-/utf8-bar-0.1.0.tgz",
"integrity": "sha512-AU+KwhlIChF/Su3d/tBrnhtDS6Bd1YWXeRc/If2/XEV/3f8LTSGJQQVONqUI6fwwTrkT5GKbdYxm7qQD7nEcCQ==",
"dev": true
},
"util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",

View File

@ -1,59 +0,0 @@
### deepMapKeys
Deep maps an object keys.
Creates an object with the same values as the provided object and keys generated by running the provided function for each key.
Use Object.keys(obj) to iterate over the object's keys. Use Array.prototype.reduce() to create a new object with the same values and mapped keys using fn.
```js
const deepMapKeys = (obj, f) => (
Array.isArray(obj)
? obj.map(val => deepMapKeys(val, f))
: (typeof obj === 'object')
? Object.keys(obj).reduce((acc, current) => {
const val = obj[current];
acc[f(current)] = (val !== null && typeof val === 'object')
? deepMapKeys(val, f)
: acc[f(current)] = val;
return acc;
}, {})
: obj
);
```
```js
'use strict';
const obj = {
foo:'1',
isnull:null,
nested:{
bar:'1',
child:{
withArray:[
{
grandChild:[ 'hello' ]
}
]
}
}
}
const upperKeysObj = deepMapKeys(obj, (key) => key.toUpperCase());
/*
Formatted JSON Data
{
"FOO":"1",
"ISNULL":null,
"NESTED":{
"BAR":"1",
"CHILD":{
"WITHARRAY":[
{
"GRANDCHILD":[ 'hello' ]
}
]
}
}
}
*/
```

View File

@ -50,7 +50,6 @@ decapitalize:string,array,intermediate
deepClone:object,recursion,intermediate
deepFlatten:array,recursion,intermediate
deepFreeze:object,recursion,intermediate
deepMapKeys:object,recursion
defaults:object,intermediate
defer:function,intermediate
degreesToRads:math,beginner

View File

@ -224,19 +224,6 @@ const deepFreeze = obj =>
prop =>
!(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
) || Object.freeze(obj);
const deepMapKeys = (obj, f) => (
Array.isArray(obj)
? obj.map(val => deepMapKeys(val, f))
: (typeof obj === 'object')
? Object.keys(obj).reduce((acc, current) => {
const val = obj[current];
acc[f(current)] = (val !== null && typeof val === 'object')
? deepMapKeys(val, f)
: acc[f(current)] = val;
return acc;
}, {})
: obj
);
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
const degreesToRads = deg => (deg * Math.PI) / 180.0;
@ -1503,4 +1490,4 @@ const speechSynthesis = message => {
const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);
module.exports = { CSVToArray, CSVToJSON, JSONToFile, JSONtoCSV, RGBToHex, URLJoin, UUIDGeneratorBrowser, UUIDGeneratorNode, all, allEqual, any, approximatelyEqual, arrayToCSV, arrayToHtmlList, ary, atob, attempt, average, averageBy, bifurcate, bifurcateBy, bind, bindAll, bindKey, binomialCoefficient, bottomVisible, btoa, byteSize, call, capitalize, capitalizeEveryWord, castArray, chainAsync, chunk, clampNumber, cloneRegExp, coalesce, coalesceFactory, collectInto, colorize, compact, compose, composeRight, converge, copyToClipboard, countBy, countOccurrences, counter, createElement, createEventHub, currentURL, curry, dayOfYear, debounce, decapitalize, deepClone, deepFlatten, deepFreeze, deepMapKeys, defaults, defer, degreesToRads, delay, detectDeviceType, difference, differenceBy, differenceWith, dig, digitize, distance, drop, dropRight, dropRightWhile, dropWhile, elementContains, elementIsVisibleInViewport, elo, equals, escapeHTML, escapeRegExp, everyNth, extendHex, factorial, fibonacci, filterNonUnique, filterNonUniqueBy, findKey, findLast, findLastIndex, findLastKey, flatten, flattenObject, flip, forEachRight, forOwn, forOwnRight, formatDuration, fromCamelCase, functionName, functions, gcd, geometricProgression, get, getColonTimeFromDate, getDaysDiffBetweenDates, getImages, getMeridiemSuffixOfInteger, getScrollPosition, getStyle, getType, getURLParameters, groupBy, hammingDistance, hasClass, hasFlags, hashBrowser, hashNode, head, hexToRGB, hide, httpGet, httpPost, httpsRedirect, hz, inRange, indentString, indexOfAll, initial, initialize2DArray, initializeArrayWithRange, initializeArrayWithRangeRight, initializeArrayWithValues, initializeNDArray, insertAfter, insertBefore, intersection, intersectionBy, intersectionWith, invertKeyValues, is, isAbsoluteURL, isAfterDate, isAnagram, isArrayLike, isBeforeDate, isBoolean, isBrowser, isBrowserTabFocused, isDivisible, isDuplexStream, isEmpty, isEven, isFunction, isLowerCase, isNegativeZero, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isPrime, isPrimitive, isPromiseLike, isReadableStream, isSameDate, isSorted, isStream, isString, isSymbol, isTravisCI, isUndefined, isUpperCase, isValidJSON, isWritableStream, join, last, lcm, longestItem, lowercaseKeys, luhnCheck, mapKeys, mapObject, mapString, mapValues, mask, matches, matchesWith, maxBy, maxDate, maxN, median, memoize, merge, minBy, minDate, minN, mostPerformant, negate, nest, nodeListToArray, none, nthArg, nthElement, objectFromPairs, objectToPairs, observeMutations, off, offset, omit, omitBy, on, onUserInputChange, once, orderBy, over, overArgs, pad, palindrome, parseCookie, partial, partialRight, partition, percentile, permutations, pick, pickBy, pipeAsyncFunctions, pipeFunctions, pluralize, powerset, prefix, prettyBytes, primes, promisify, pull, pullAtIndex, pullAtValue, pullBy, radsToDegrees, randomHexColorCode, randomIntArrayInRange, randomIntegerInRange, randomNumberInRange, readFileLines, rearg, recordAnimationFrames, redirect, reduceSuccessive, reduceWhich, reducedFilter, reject, remove, removeNonASCII, renameKeys, reverseString, round, runAsync, runPromisesInSeries, sample, sampleSize, scrollToTop, sdbm, serializeCookie, setStyle, shallowClone, shank, show, shuffle, similarity, size, sleep, smoothScroll, sortCharactersInString, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, splitLines, spreadOver, stableSort, standardDeviation, stringPermutations, stripHTMLTags, sum, sumBy, sumPower, symmetricDifference, symmetricDifferenceBy, symmetricDifferenceWith, tail, take, takeRight, takeRightWhile, takeWhile, throttle, timeTaken, times, toCamelCase, toCurrency, toDecimalMark, toHash, toKebabCase, toOrdinalSuffix, toSafeInteger, toSnakeCase, toTitleCase, toggleClass, tomorrow, transform, triggerEvent, truncateString, truthCheckCollection, unary, uncurry, unescapeHTML, unflattenObject, unfold, union, unionBy, unionWith, uniqueElements, uniqueElementsBy, uniqueElementsByRight, uniqueSymmetricDifference, untildify, unzip, unzipWith, validateNumber, when, without, words, xProd, yesNo, zip, zipObject, zipWith, JSONToDate, binarySearch, celsiusToFahrenheit, cleanObj, collatz, countVowels, factors, fahrenheitToCelsius, fibonacciCountUntilNum, fibonacciUntilNum, heronArea, howManyTimes, httpDelete, httpPut, isArmstrongNumber, isSimilar, kmphToMph, levenshteinDistance, mphToKmph, pipeLog, quickSort, removeVowels, solveRPN, speechSynthesis, squareSum }
module.exports = {CSVToArray,CSVToJSON,JSONToFile,JSONtoCSV,RGBToHex,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,all,allEqual,any,approximatelyEqual,arrayToCSV,arrayToHtmlList,ary,atob,attempt,average,averageBy,bifurcate,bifurcateBy,bind,bindAll,bindKey,binomialCoefficient,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,countOccurrences,counter,createElement,createEventHub,currentURL,curry,dayOfYear,debounce,decapitalize,deepClone,deepFlatten,deepFreeze,defaults,defer,degreesToRads,delay,detectDeviceType,difference,differenceBy,differenceWith,dig,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementContains,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,filterNonUniqueBy,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getImages,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,hz,inRange,indentString,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,initializeNDArray,insertAfter,insertBefore,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isAfterDate,isAnagram,isArrayLike,isBeforeDate,isBoolean,isBrowser,isBrowserTabFocused,isDivisible,isDuplexStream,isEmpty,isEven,isFunction,isLowerCase,isNegativeZero,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isReadableStream,isSameDate,isSorted,isStream,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,isWritableStream,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapString,mapValues,mask,matches,matchesWith,maxBy,maxDate,maxN,median,memoize,merge,minBy,minDate,minN,mostPerformant,negate,nest,nodeListToArray,none,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,offset,omit,omitBy,on,onUserInputChange,once,orderBy,over,overArgs,pad,palindrome,parseCookie,partial,partialRight,partition,percentile,permutations,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prefix,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,radsToDegrees,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,recordAnimationFrames,redirect,reduceSuccessive,reduceWhich,reducedFilter,reject,remove,removeNonASCII,renameKeys,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,shank,show,shuffle,similarity,size,sleep,smoothScroll,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,stableSort,standardDeviation,stringPermutations,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,timeTaken,times,toCamelCase,toCurrency,toDecimalMark,toHash,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toTitleCase,toggleClass,tomorrow,transform,triggerEvent,truncateString,truthCheckCollection,unary,uncurry,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,uniqueElementsBy,uniqueElementsByRight,uniqueSymmetricDifference,untildify,unzip,unzipWith,validateNumber,when,without,words,xProd,yesNo,zip,zipObject,zipWith,JSONToDate,binarySearch,celsiusToFahrenheit,cleanObj,collatz,countVowels,factors,fahrenheitToCelsius,fibonacciCountUntilNum,fibonacciUntilNum,heronArea,howManyTimes,httpDelete,httpPut,isArmstrongNumber,isSimilar,kmphToMph,levenshteinDistance,mphToKmph,pipeLog,quickSort,removeVowels,solveRPN,speechSynthesis,squareSum}

View File

@ -1,32 +0,0 @@
const expect = require('expect');
const { deepMapKeys, toCamelCase } = require('./_30s.js');
test('deepMapKeys is a Function', () => {
expect(deepMapKeys).toBeInstanceOf(Function);
});
test('Deep maps object keys', () => {
const obj = {
'foo_bar': 'hello',
'deep_child': {
'child_array': ['hello'],
'child_object_array': [
{ 'hola_hello': 'Gamarjoba' }
]
}
};
const expected = {
fooBar: 'hello',
deepChild: {
childArray: ['hello'],
childObjectArray: [
{
holaHello: 'Gamarjoba'
}
]
}
};
const camleCaseKeys = k => toCamelCase(k);
expect(deepMapKeys(obj, camleCaseKeys)).toEqual(expected);
});