UNPKG

21 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
7var functions = require('./functions-b6202a08.js');
8require('folktale/concurrency/task');
9var R = require('ramda');
10require('folktale/result');
11require('ramda-maybe');
12require('util');
13var throwingFunctions = require('./throwingFunctions.js');
14require('folktale/maybe');
15var monadHelpers = require('./monadHelpers-e0c6950d.js');
16var NamedTupleMap = _interopDefault(require('namedtuplemap'));
17
18/**
19 * Created by Andy Likuski on 2018.12.28
20 * Copyright (c) 2018 Andy Likuski
21 *
22 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
23 *
24 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
25 *
26 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 */
28/**
29 *
30 * Code modified from memoize-immutable. Memoizes a function using a flatArg version of the args
31 * @param {Function} fn Function expecting any number of arguments
32 * @returns {function([*], Object)} A function expecting
33 * an array of the normal args for the second argument
34 * an object of flattened args for the first argument
35 */
36
37var memoize = function memoize(fn) {
38 var cache = new NamedTupleMap();
39 var memoized = R.curry(function (normalArgs, flatArg) {
40 if (!cache.has(flatArg)) {
41 var result = R.apply(fn, normalArgs);
42 cache.set(flatArg, result);
43 return result;
44 }
45
46 return cache.get(flatArg);
47 }); // Give a meaningful displayName to the memoized function
48
49 if (fn.name) {
50 memoized.displayName = fn.name + 'Memoized';
51 }
52
53 return memoized;
54};
55/** *
56 * Memomizes a function to a single argument function so that we can always NamedTupleMap for the cache.
57 * In order for this to work all objects have to be flattened into one big object. This Cache won't
58 * accept inner objects that have changed. So the function coverts three args like
59 * {a: {wombat: 1, emu: 2}}, {b: {caracal: 1, serval: 2}}, 'hamster' to
60 * {arg1.a: {wombat: 1, emu: 2}, arg2.b: {caracal: 1, serval: 2}, arg3: 'hamster}.
61 * You can provide any depth of objects as arguments, but it will have performance penalties
62 * Consider memoizedWith to filter out unimportant data from arguments
63 * @param {Function} func A function with any number and type of args
64 * @returns {Function} A function that expects the same args as func
65 */
66
67
68var memoized = function memoized(func) {
69 return memoizedWith(function () {
70 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
71 args[_key] = arguments[_key];
72 }
73
74 return args;
75 }, func);
76};
77/** *
78 * Memomizes a function to a single argument function so that we can always NamedTupleMap for the cache.
79 * In order for this to work all objects have to be flattened into one big object. This Cache won't
80 * accept inner objects that have changed. So the function coverts three args like
81 * {a: {wombat: 1, emu: 2}}, {b: {caracal: 1, serval: 2}}, 'hamster' to
82 * {arg1.a: {wombat: 1, emu: 2}, arg2.b: {caracal: 1, serval: 2}, arg3: 'hamster}.
83 * You can provide any depth of objects as arguments, but it will have performance penalties.
84 * To simplify the arguments and remove incomparable things like functions, use argumentFilter.
85 * @param {Function} argumentFilter Expects the same number of arguments as func and returns an equal
86 * number in an array. Each argument can be filtered to remove expensive objects or functions. Make
87 * sure not to filter out anything that is used by func, since it will not figure into the argument uniqueness
88 * @param {Function} func A function with any number and type of args. argumentFilter must match it
89 * @returns {Function} A function that expects the same args as func. This function is curried, expecting
90 * whatever number of arguments func is declared with, so you can call it partially
91 */
92
93var memoizedWith = function memoizedWith(argumentFilter, func) {
94 // memoize(func) returns the memoized function expecting args and the flattened obj
95 var memo = memoize(func); // Returns a function expecting the args for fun
96
97 return R.curryN(func.length, function () {
98 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
99 args[_key2] = arguments[_key2];
100 }
101
102 // Function that flattens the original args and called memoizedFunc with the single flattened arg
103 return R.compose(memo(args), functions.flattenObj, // Filter out unneeded parts of the arguments, or does nothing if argumentFilter is ...args => args
104 R.apply(argumentFilter))(args);
105 });
106};
107
108var isObject = R.compose(R.equals('Object'), R.type);
109var allAreObjectsOrLists = R.compose(R.either(R.all(isObject), R.all(Array.isArray)), R.values);
110
111var hasVersion = function hasVersion(versionLabel) {
112 return function (obj) {
113 return R.has(versionLabel, obj);
114 };
115};
116
117var hasBoth = function hasBoth(versionLabels) {
118 return function (obj) {
119 return R.all(function (versionLabel) {
120 return hasVersion(versionLabel)(obj);
121 }, versionLabels);
122 };
123};
124
125var isEqual = function isEqual(versionLabels) {
126 return function (obj) {
127 return R.both(hasBoth(versionLabels), R.compose(R.apply(R.equals), R.values))(obj);
128 };
129};
130
131var markAdded = function markAdded(obj) {
132 return R.compose(R.append(undefined), R.values)(obj);
133}; // eslint-disable-line no-undefined
134
135
136var markRemoved = function markRemoved(obj) {
137 return R.compose(R.prepend(undefined), R.values)(obj);
138}; // eslint-disable-line no-undefined
139
140
141var isAddition = function isAddition(versionLabels) {
142 return function (obj) {
143 return R.both(hasVersion(R.head(versionLabels)), R.complement(hasVersion(R.last(versionLabels))))(obj);
144 };
145};
146
147var isRemoval = function isRemoval(versionLabels) {
148 return function (obj) {
149 return R.both(R.complement(hasVersion(R.head(versionLabels))), hasVersion(R.last(versionLabels)))(obj);
150 };
151};
152/**
153 * Diffs objects and replaces differences with an object {__left: left value, __right: right value}
154 * @param {[String]} Two values indicating the names of the versions. If left null then __left and __right
155 * are used for the diff
156 * @param {Object} l The left object to diff
157 * @param {Object} r The right object to diff
158 * @returns {Object} A deep diff of l and r. Equal values are removed, different values are replaced by an
159 * object keyed by the two version strings with the corresponding values
160 */
161
162
163var objectDiff = R.curry(function (versionLabels, l, r) {
164 var labels = R.defaultTo(['__left', '__right'], versionLabels);
165
166 var _labels = functions._slicedToArray(labels, 2),
167 left = _labels[0],
168 right = _labels[1];
169
170 return R.compose(function (result) {
171 return R.map(R.cond([[function (obj) {
172 return isAddition(labels)(obj);
173 }, function (obj) {
174 return markAdded(obj);
175 }], [function (obj) {
176 return isRemoval(labels)(obj);
177 }, function (obj) {
178 return markRemoved(obj);
179 }], [function (obj) {
180 return hasBoth(labels)(obj);
181 }, function (obj) {
182 return R.when(allAreObjectsOrLists, // If all are objects or list recurse
183 // Lists necessary become objects keyed by index since some indices are removed
184 function (o) {
185 return R.compose( // Remove the left, right labels and recurse
186 function (values) {
187 return R.apply(objectDiff(versionLabels), values);
188 }, R.values)(o);
189 } // Otherwise we keep the left and right labels and we are done
190 )(obj);
191 }]]), result);
192 }, function (result) {
193 return R.reject(function (obj) {
194 return isEqual(labels)(obj);
195 }, result);
196 }, R.useWith(R.mergeWith(R.merge), [R.map(R.objOf(left)), R.map(R.objOf(right))]))(l, r);
197});
198/**
199 * Pretty-prints objectDiff
200 * @param {[String]} versionLabels The two labels or null
201 * @param {Object} l The left-side value
202 * @param {Object} r The right-side value
203 * @returns {String} The diff string
204 */
205
206var prettyPrintObjectDiff = function prettyPrintObjectDiff(versionLabels, l, r) {
207 return R.compose(function (result) {
208 return JSON.stringify(result, null, 2);
209 }, objectDiff)(versionLabels, l, r);
210};
211
212/**
213 * Created by Andy Likuski on 2017.06.06
214 * Copyright (c) 2017 Andy Likuski
215 *
216 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
217 *
218 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
219 *
220 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
221 */
222/**
223 * Given a task, wraps it in promise and passes it to Jest's expect.
224 * With this you can call resolves or rejects depending on whether success or failure is expected:
225 * expectTask(task).resolves|rejects
226 * @param {Task} task Task wrapped in a Promise and forked
227 * @returns {undefined}
228 */
229
230var expectTask = function expectTask(task) {
231 return expect(monadHelpers.taskToPromise(task));
232};
233/**
234 * Converts an Result to a Promise. Result.Ok calls resolve and Result.Error calls reject
235 * @param {Object} result A Result
236 * @returns {Promise} the promise
237 */
238
239var resultToPromise = function resultToPromise(result) {
240 return new Promise(function (resolve, reject) {
241 return result.map(resolve).mapError(reject);
242 });
243};
244/**
245 * Convenient way to check if an object has a few expected keys at the given path
246 * @param {[String]} keyPaths keys or dot-separated key paths of the object to check
247 * @param {Object} obj The object to check
248 * @return {*} Expects the object has the given keys. Throws if expect fails* @return {*}
249 */
250
251var expectKeys = R.curry(function (keyPaths, obj) {
252 expect(R.compose( // Put the keyPaths that survive in a set for comparison
253 function (a) {
254 return new Set(a);
255 }, // Filter out keyPaths that don't resolve to a non-nil value
256 function (o) {
257 return R.filter(function (keyPath) {
258 return R.complement(R.isNil)(R.view(R.lensPath(functions.keyStringToLensPath(keyPath)), o));
259 }, keyPaths);
260 })(obj)).toEqual(new Set(keyPaths)); // Required for validated functions
261
262 return true;
263});
264/**
265 * Convenient way to check if an object has a few expected keys at the given path
266 * @param {[String]} keyPaths keys or dot-separated key paths of the object to check
267 * @param {String} strPath path in the obj to check keyPaths for
268 * @param {Object} obj The object to check
269 * @return {*} Expects the object has the given keys. Throws if expect fails* @return {*}
270 */
271
272var expectKeysAtPath = R.curry(function (keyPaths, strPath, obj) {
273 expect(R.compose( // Put the keyPaths that survive in a set for comparison
274 function (a) {
275 return new Set(a);
276 }, // Filter out keyPaths that don't resolve to a non-nil value
277 function (o) {
278 return R.filter(function (keyPath) {
279 return R.complement(R.isNil)(R.view(R.lensPath(functions.keyStringToLensPath(keyPath)), throwingFunctions.reqStrPathThrowing(strPath, o)));
280 }, keyPaths);
281 })(obj)).toEqual(new Set(keyPaths)); // Required for validated functions
282
283 return true;
284});
285
286exports.alwaysFunc = functions.alwaysFunc;
287exports.applyDeep = functions.applyDeep;
288exports.applyDeepAndMapObjs = functions.applyDeepAndMapObjs;
289exports.camelCase = functions.camelCase;
290exports.capitalize = functions.capitalize;
291exports.chainObjToValues = functions.chainObjToValues;
292exports.compact = functions.compact;
293exports.compactEmpty = functions.compactEmpty;
294exports.compactJoin = functions.compactJoin;
295exports.duplicateKey = functions.duplicateKey;
296exports.emptyToNull = functions.emptyToNull;
297exports.eqStrPath = functions.eqStrPath;
298exports.eqStrPathsAll = functions.eqStrPathsAll;
299exports.filterObjToValues = functions.filterObjToValues;
300exports.filterWithKeys = functions.filterWithKeys;
301exports.findByParams = functions.findByParams;
302exports.findMapped = functions.findMapped;
303exports.findOne = functions.findOne;
304exports.findOneValueByParams = functions.findOneValueByParams;
305exports.flattenObj = functions.flattenObj;
306exports.flattenObjUntil = functions.flattenObjUntil;
307exports.fromPairsDeep = functions.fromPairsDeep;
308exports.hasStrPath = functions.hasStrPath;
309exports.idOrIdFromObj = functions.idOrIdFromObj;
310exports.isObject = functions.isObject;
311exports.keyStringToLensPath = functions.keyStringToLensPath;
312exports.lowercase = functions.lowercase;
313exports.mapDefault = functions.mapDefault;
314exports.mapDefaultAndPrefixOthers = functions.mapDefaultAndPrefixOthers;
315exports.mapKeys = functions.mapKeys;
316exports.mapKeysAndValues = functions.mapKeysAndValues;
317exports.mapKeysForLens = functions.mapKeysForLens;
318exports.mapObjToValues = functions.mapObjToValues;
319exports.mapProp = functions.mapProp;
320exports.mapPropValueAsIndex = functions.mapPropValueAsIndex;
321exports.mapToObjValue = functions.mapToObjValue;
322exports.mergeAllWithKey = functions.mergeAllWithKey;
323exports.mergeDeep = functions.mergeDeep;
324exports.mergeDeepAll = functions.mergeDeepAll;
325exports.mergeDeepWith = functions.mergeDeepWith;
326exports.mergeDeepWithConcatArrays = functions.mergeDeepWithConcatArrays;
327exports.mergeDeepWithRecurseArrayItems = functions.mergeDeepWithRecurseArrayItems;
328exports.mergeDeepWithRecurseArrayItemsAndMapObjs = functions.mergeDeepWithRecurseArrayItemsAndMapObjs;
329exports.mergeDeepWithRecurseArrayItemsByAndMergeObjectByRight = functions.mergeDeepWithRecurseArrayItemsByAndMergeObjectByRight;
330exports.mergeDeepWithRecurseArrayItemsByRight = functions.mergeDeepWithRecurseArrayItemsByRight;
331exports.moveToKeys = functions.moveToKeys;
332exports.omitDeep = functions.omitDeep;
333exports.omitDeepBy = functions.omitDeepBy;
334exports.omitDeepPaths = functions.omitDeepPaths;
335exports.onlyOne = functions.onlyOne;
336exports.onlyOneValue = functions.onlyOneValue;
337exports.orEmpty = functions.orEmpty;
338exports.overDeep = functions.overDeep;
339exports.pickDeepPaths = functions.pickDeepPaths;
340exports.removeDuplicateObjectsByProp = functions.removeDuplicateObjectsByProp;
341exports.renameKey = functions.renameKey;
342exports.replaceValuesAtDepth = functions.replaceValuesAtDepth;
343exports.replaceValuesAtDepthAndStringify = functions.replaceValuesAtDepthAndStringify;
344exports.replaceValuesWithCountAtDepth = functions.replaceValuesWithCountAtDepth;
345exports.replaceValuesWithCountAtDepthAndStringify = functions.replaceValuesWithCountAtDepthAndStringify;
346exports.reqPath = functions.reqPath;
347exports.reqPathPropEq = functions.reqPathPropEq;
348exports.reqStrPath = functions.reqStrPath;
349exports.splitAtInclusive = functions.splitAtInclusive;
350exports.strPath = functions.strPath;
351exports.strPathOr = functions.strPathOr;
352exports.strPathOrNullOk = functions.strPathOrNullOk;
353exports.toArrayIfNot = functions.toArrayIfNot;
354exports.transformKeys = functions.transformKeys;
355exports.unflattenObj = functions.unflattenObj;
356exports.unflattenObjNoArrays = functions.unflattenObjNoArrays;
357exports.findOneThrowing = throwingFunctions.findOneThrowing;
358exports.findOneValueByParamsThrowing = throwingFunctions.findOneValueByParamsThrowing;
359exports.mappedThrowIfResultError = throwingFunctions.mappedThrowIfResultError;
360exports.onlyOneThrowing = throwingFunctions.onlyOneThrowing;
361exports.onlyOneValueThrowing = throwingFunctions.onlyOneValueThrowing;
362exports.reqPathPropEqThrowing = throwingFunctions.reqPathPropEqThrowing;
363exports.reqPathThrowing = throwingFunctions.reqPathThrowing;
364exports.reqStrPathThrowing = throwingFunctions.reqStrPathThrowing;
365exports.throwIfResultError = throwingFunctions.throwIfResultError;
366exports.throwIfSingleResultError = throwingFunctions.throwIfSingleResultError;
367exports.chainExceptMapDeepestMDeep = monadHelpers.chainExceptMapDeepestMDeep;
368exports.chainMDeep = monadHelpers.chainMDeep;
369exports.composeWithChain = monadHelpers.composeWithChain;
370exports.composeWithChainMDeep = monadHelpers.composeWithChainMDeep;
371exports.composeWithMap = monadHelpers.composeWithMap;
372exports.composeWithMapExceptChainDeepestMDeep = monadHelpers.composeWithMapExceptChainDeepestMDeep;
373exports.composeWithMapMDeep = monadHelpers.composeWithMapMDeep;
374exports.defaultRunConfig = monadHelpers.defaultRunConfig;
375exports.defaultRunToResultConfig = monadHelpers.defaultRunToResultConfig;
376exports.doMDeep = monadHelpers.doMDeep;
377exports.doMDeepExceptDeepest = monadHelpers.doMDeepExceptDeepest;
378exports.lift1stOf2ForMDeepMonad = monadHelpers.lift1stOf2ForMDeepMonad;
379exports.mapExceptChainDeepestMDeep = monadHelpers.mapExceptChainDeepestMDeep;
380exports.mapMDeep = monadHelpers.mapMDeep;
381exports.mapMonadByConfig = monadHelpers.mapMonadByConfig;
382exports.mapOrObjToNamedResponseAndInputs = monadHelpers.mapOrObjToNamedResponseAndInputs;
383exports.mapResultMonadWithOtherInputs = monadHelpers.mapResultMonadWithOtherInputs;
384exports.mapResultTaskWithOtherInputs = monadHelpers.mapResultTaskWithOtherInputs;
385exports.mapToMergedResponseAndInputs = monadHelpers.mapToMergedResponseAndInputs;
386exports.mapToMergedResponseAndInputsMDeep = monadHelpers.mapToMergedResponseAndInputsMDeep;
387exports.mapToNamedPathAndInputs = monadHelpers.mapToNamedPathAndInputs;
388exports.mapToNamedResponseAndInputs = monadHelpers.mapToNamedResponseAndInputs;
389exports.mapToNamedResponseAndInputsMDeep = monadHelpers.mapToNamedResponseAndInputsMDeep;
390exports.mapToPath = monadHelpers.mapToPath;
391exports.mapToResponseAndInputs = monadHelpers.mapToResponseAndInputs;
392exports.mapWithArgToPath = monadHelpers.mapWithArgToPath;
393exports.objOfMLevelDeepListOfMonadsToListWithPairs = monadHelpers.objOfMLevelDeepListOfMonadsToListWithPairs;
394exports.objOfMLevelDeepMonadsToListWithPairs = monadHelpers.objOfMLevelDeepMonadsToListWithPairs;
395exports.pairsOfMLevelDeepListOfMonadsToListWithPairs = monadHelpers.pairsOfMLevelDeepListOfMonadsToListWithPairs;
396exports.promiseToTask = monadHelpers.promiseToTask;
397exports.resultTasksToResultObjTask = monadHelpers.resultTasksToResultObjTask;
398exports.resultToTask = monadHelpers.resultToTask;
399exports.resultToTaskNeedingResult = monadHelpers.resultToTaskNeedingResult;
400exports.resultToTaskWithResult = monadHelpers.resultToTaskWithResult;
401exports.resultsToResultObj = monadHelpers.resultsToResultObj;
402exports.retryTask = monadHelpers.retryTask;
403exports.sequenceBucketed = monadHelpers.sequenceBucketed;
404exports.stringifyError = monadHelpers.stringifyError;
405exports.taskToPromise = monadHelpers.taskToPromise;
406exports.taskToResultTask = monadHelpers.taskToResultTask;
407exports.toMergedResponseAndInputs = monadHelpers.toMergedResponseAndInputs;
408exports.toNamedResponseAndInputs = monadHelpers.toNamedResponseAndInputs;
409exports.traverseReduce = monadHelpers.traverseReduce;
410exports.traverseReduceDeep = monadHelpers.traverseReduceDeep;
411exports.traverseReduceDeepResults = monadHelpers.traverseReduceDeepResults;
412exports.traverseReduceError = monadHelpers.traverseReduceError;
413exports.traverseReduceResultError = monadHelpers.traverseReduceResultError;
414exports.traverseReduceWhile = monadHelpers.traverseReduceWhile;
415exports.traverseReduceWhileBucketed = monadHelpers.traverseReduceWhileBucketed;
416exports.traverseReduceWhileBucketedTasks = monadHelpers.traverseReduceWhileBucketedTasks;
417exports.waitAllBucketed = monadHelpers.waitAllBucketed;
418exports.expectKeys = expectKeys;
419exports.expectKeysAtPath = expectKeysAtPath;
420exports.expectTask = expectTask;
421exports.memoized = memoized;
422exports.memoizedWith = memoizedWith;
423exports.objectDiff = objectDiff;
424exports.prettyPrintObjectDiff = prettyPrintObjectDiff;
425exports.resultToPromise = resultToPromise;
426//# sourceMappingURL=index.js.map