UNPKG

19.4 kBJavaScriptView Raw
1"use strict";
2var __spreadArrays = (this && this.__spreadArrays) || function () {
3 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
4 for (var r = Array(s), k = 0, i = 0; i < il; i++)
5 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
6 r[k] = a[j];
7 return r;
8};
9Object.defineProperty(exports, "__esModule", { value: true });
10exports.silentRejection = exports.silenceUncaughtInPromise = exports._extend = exports.copy = exports.tail = exports.applyPairs = exports.arrayTuples = exports.pairs = exports.assertFn = exports.assertMap = exports.assertPredicate = exports.flatten = exports.unnest = exports.uniqR = exports.pushR = exports.flattenR = exports.unnestR = exports.anyTrueR = exports.allTrueR = exports.values = exports.map = exports.mapObj = exports.find = exports.filter = exports.pluck = exports.omit = exports.pick = exports.ancestors = exports.mergeR = exports.defaults = exports.deregAll = exports._pushTo = exports.pushTo = exports._removeFrom = exports.removeFrom = exports._inArray = exports.inArray = exports.inherit = exports.createProxyFunctions = exports.noop = exports.identity = exports.equals = exports.extend = exports.forEach = exports.toJson = exports.fromJson = exports.root = void 0;
11/**
12 * Random utility functions used in the UI-Router code
13 *
14 * These functions are exported, but are subject to change without notice.
15 *
16 * @packageDocumentation
17 * @preferred
18 */
19var predicates_1 = require("./predicates");
20var hof_1 = require("./hof");
21var coreservices_1 = require("./coreservices");
22exports.root = (typeof self === 'object' && self.self === self && self) ||
23 (typeof global === 'object' && global.global === global && global) ||
24 this;
25var angular = exports.root.angular || {};
26exports.fromJson = angular.fromJson || JSON.parse.bind(JSON);
27exports.toJson = angular.toJson || JSON.stringify.bind(JSON);
28exports.forEach = angular.forEach || _forEach;
29exports.extend = Object.assign || _extend;
30exports.equals = angular.equals || _equals;
31function identity(x) {
32 return x;
33}
34exports.identity = identity;
35function noop() { }
36exports.noop = noop;
37/**
38 * Builds proxy functions on the `to` object which pass through to the `from` object.
39 *
40 * For each key in `fnNames`, creates a proxy function on the `to` object.
41 * The proxy function calls the real function on the `from` object.
42 *
43 *
44 * #### Example:
45 * This example creates an new class instance whose functions are prebound to the new'd object.
46 * ```js
47 * class Foo {
48 * constructor(data) {
49 * // Binds all functions from Foo.prototype to 'this',
50 * // then copies them to 'this'
51 * bindFunctions(Foo.prototype, this, this);
52 * this.data = data;
53 * }
54 *
55 * log() {
56 * console.log(this.data);
57 * }
58 * }
59 *
60 * let myFoo = new Foo([1,2,3]);
61 * var logit = myFoo.log;
62 * logit(); // logs [1, 2, 3] from the myFoo 'this' instance
63 * ```
64 *
65 * #### Example:
66 * This example creates a bound version of a service function, and copies it to another object
67 * ```
68 *
69 * var SomeService = {
70 * this.data = [3, 4, 5];
71 * this.log = function() {
72 * console.log(this.data);
73 * }
74 * }
75 *
76 * // Constructor fn
77 * function OtherThing() {
78 * // Binds all functions from SomeService to SomeService,
79 * // then copies them to 'this'
80 * bindFunctions(SomeService, this, SomeService);
81 * }
82 *
83 * let myOtherThing = new OtherThing();
84 * myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this'
85 * ```
86 *
87 * @param source A function that returns the source object which contains the original functions to be bound
88 * @param target A function that returns the target object which will receive the bound functions
89 * @param bind A function that returns the object which the functions will be bound to
90 * @param fnNames The function names which will be bound (Defaults to all the functions found on the 'from' object)
91 * @param latebind If true, the binding of the function is delayed until the first time it's invoked
92 */
93function createProxyFunctions(source, target, bind, fnNames, latebind) {
94 if (latebind === void 0) { latebind = false; }
95 var bindFunction = function (fnName) { return source()[fnName].bind(bind()); };
96 var makeLateRebindFn = function (fnName) {
97 return function lateRebindFunction() {
98 target[fnName] = bindFunction(fnName);
99 return target[fnName].apply(null, arguments);
100 };
101 };
102 fnNames = fnNames || Object.keys(source());
103 return fnNames.reduce(function (acc, name) {
104 acc[name] = latebind ? makeLateRebindFn(name) : bindFunction(name);
105 return acc;
106 }, target);
107}
108exports.createProxyFunctions = createProxyFunctions;
109/**
110 * prototypal inheritance helper.
111 * Creates a new object which has `parent` object as its prototype, and then copies the properties from `extra` onto it
112 */
113exports.inherit = function (parent, extra) { return exports.extend(Object.create(parent), extra); };
114/** Given an array, returns true if the object is found in the array, (using indexOf) */
115exports.inArray = hof_1.curry(_inArray);
116function _inArray(array, obj) {
117 return array.indexOf(obj) !== -1;
118}
119exports._inArray = _inArray;
120/**
121 * Given an array, and an item, if the item is found in the array, it removes it (in-place).
122 * The same array is returned
123 */
124exports.removeFrom = hof_1.curry(_removeFrom);
125function _removeFrom(array, obj) {
126 var idx = array.indexOf(obj);
127 if (idx >= 0)
128 array.splice(idx, 1);
129 return array;
130}
131exports._removeFrom = _removeFrom;
132/** pushes a values to an array and returns the value */
133exports.pushTo = hof_1.curry(_pushTo);
134function _pushTo(arr, val) {
135 return arr.push(val), val;
136}
137exports._pushTo = _pushTo;
138/** Given an array of (deregistration) functions, calls all functions and removes each one from the source array */
139exports.deregAll = function (functions) {
140 return functions.slice().forEach(function (fn) {
141 typeof fn === 'function' && fn();
142 exports.removeFrom(functions, fn);
143 });
144};
145/**
146 * Applies a set of defaults to an options object. The options object is filtered
147 * to only those properties of the objects in the defaultsList.
148 * Earlier objects in the defaultsList take precedence when applying defaults.
149 */
150function defaults(opts) {
151 var defaultsList = [];
152 for (var _i = 1; _i < arguments.length; _i++) {
153 defaultsList[_i - 1] = arguments[_i];
154 }
155 var defaultVals = exports.extend.apply(void 0, __spreadArrays([{}], defaultsList.reverse()));
156 return exports.extend(defaultVals, pick(opts || {}, Object.keys(defaultVals)));
157}
158exports.defaults = defaults;
159/** Reduce function that merges each element of the list into a single object, using extend */
160exports.mergeR = function (memo, item) { return exports.extend(memo, item); };
161/**
162 * Finds the common ancestor path between two states.
163 *
164 * @param {Object} first The first state.
165 * @param {Object} second The second state.
166 * @return {Array} Returns an array of state names in descending order, not including the root.
167 */
168function ancestors(first, second) {
169 var path = [];
170 // tslint:disable-next-line:forin
171 for (var n in first.path) {
172 if (first.path[n] !== second.path[n])
173 break;
174 path.push(first.path[n]);
175 }
176 return path;
177}
178exports.ancestors = ancestors;
179/**
180 * Return a copy of the object only containing the whitelisted properties.
181 *
182 * #### Example:
183 * ```
184 * var foo = { a: 1, b: 2, c: 3 };
185 * var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 }
186 * ```
187 * @param obj the source object
188 * @param propNames an Array of strings, which are the whitelisted property names
189 */
190function pick(obj, propNames) {
191 var objCopy = {};
192 for (var _prop in obj) {
193 if (propNames.indexOf(_prop) !== -1) {
194 objCopy[_prop] = obj[_prop];
195 }
196 }
197 return objCopy;
198}
199exports.pick = pick;
200/**
201 * Return a copy of the object omitting the blacklisted properties.
202 *
203 * @example
204 * ```
205 *
206 * var foo = { a: 1, b: 2, c: 3 };
207 * var ab = omit(foo, ['a', 'b']); // { c: 3 }
208 * ```
209 * @param obj the source object
210 * @param propNames an Array of strings, which are the blacklisted property names
211 */
212function omit(obj, propNames) {
213 return Object.keys(obj)
214 .filter(hof_1.not(exports.inArray(propNames)))
215 .reduce(function (acc, key) { return ((acc[key] = obj[key]), acc); }, {});
216}
217exports.omit = omit;
218/**
219 * Maps an array, or object to a property (by name)
220 */
221function pluck(collection, propName) {
222 return map(collection, hof_1.prop(propName));
223}
224exports.pluck = pluck;
225/** Filters an Array or an Object's properties based on a predicate */
226function filter(collection, callback) {
227 var arr = predicates_1.isArray(collection), result = arr ? [] : {};
228 var accept = arr ? function (x) { return result.push(x); } : function (x, key) { return (result[key] = x); };
229 exports.forEach(collection, function (item, i) {
230 if (callback(item, i))
231 accept(item, i);
232 });
233 return result;
234}
235exports.filter = filter;
236/** Finds an object from an array, or a property of an object, that matches a predicate */
237function find(collection, callback) {
238 var result;
239 exports.forEach(collection, function (item, i) {
240 if (result)
241 return;
242 if (callback(item, i))
243 result = item;
244 });
245 return result;
246}
247exports.find = find;
248/** Given an object, returns a new object, where each property is transformed by the callback function */
249exports.mapObj = map;
250/** Maps an array or object properties using a callback function */
251function map(collection, callback, target) {
252 target = target || (predicates_1.isArray(collection) ? [] : {});
253 exports.forEach(collection, function (item, i) { return (target[i] = callback(item, i)); });
254 return target;
255}
256exports.map = map;
257/**
258 * Given an object, return its enumerable property values
259 *
260 * @example
261 * ```
262 *
263 * let foo = { a: 1, b: 2, c: 3 }
264 * let vals = values(foo); // [ 1, 2, 3 ]
265 * ```
266 */
267exports.values = function (obj) { return Object.keys(obj).map(function (key) { return obj[key]; }); };
268/**
269 * Reduce function that returns true if all of the values are truthy.
270 *
271 * @example
272 * ```
273 *
274 * let vals = [ 1, true, {}, "hello world"];
275 * vals.reduce(allTrueR, true); // true
276 *
277 * vals.push(0);
278 * vals.reduce(allTrueR, true); // false
279 * ```
280 */
281exports.allTrueR = function (memo, elem) { return memo && elem; };
282/**
283 * Reduce function that returns true if any of the values are truthy.
284 *
285 * * @example
286 * ```
287 *
288 * let vals = [ 0, null, undefined ];
289 * vals.reduce(anyTrueR, true); // false
290 *
291 * vals.push("hello world");
292 * vals.reduce(anyTrueR, true); // true
293 * ```
294 */
295exports.anyTrueR = function (memo, elem) { return memo || elem; };
296/**
297 * Reduce function which un-nests a single level of arrays
298 * @example
299 * ```
300 *
301 * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];
302 * input.reduce(unnestR, []) // [ "a", "b", "c", "d", [ "double, "nested" ] ]
303 * ```
304 */
305exports.unnestR = function (memo, elem) { return memo.concat(elem); };
306/**
307 * Reduce function which recursively un-nests all arrays
308 *
309 * @example
310 * ```
311 *
312 * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];
313 * input.reduce(unnestR, []) // [ "a", "b", "c", "d", "double, "nested" ]
314 * ```
315 */
316exports.flattenR = function (memo, elem) {
317 return predicates_1.isArray(elem) ? memo.concat(elem.reduce(exports.flattenR, [])) : pushR(memo, elem);
318};
319/**
320 * Reduce function that pushes an object to an array, then returns the array.
321 * Mostly just for [[flattenR]] and [[uniqR]]
322 */
323function pushR(arr, obj) {
324 arr.push(obj);
325 return arr;
326}
327exports.pushR = pushR;
328/** Reduce function that filters out duplicates */
329exports.uniqR = function (acc, token) { return (exports.inArray(acc, token) ? acc : pushR(acc, token)); };
330/**
331 * Return a new array with a single level of arrays unnested.
332 *
333 * @example
334 * ```
335 *
336 * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];
337 * unnest(input) // [ "a", "b", "c", "d", [ "double, "nested" ] ]
338 * ```
339 */
340exports.unnest = function (arr) { return arr.reduce(exports.unnestR, []); };
341/**
342 * Return a completely flattened version of an array.
343 *
344 * @example
345 * ```
346 *
347 * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];
348 * flatten(input) // [ "a", "b", "c", "d", "double, "nested" ]
349 * ```
350 */
351exports.flatten = function (arr) { return arr.reduce(exports.flattenR, []); };
352/**
353 * Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass.
354 * @example
355 * ```
356 *
357 * let isNumber = (obj) => typeof(obj) === 'number';
358 * let allNumbers = [ 1, 2, 3, 4, 5 ];
359 * allNumbers.filter(assertPredicate(isNumber)); //OK
360 *
361 * let oneString = [ 1, 2, 3, 4, "5" ];
362 * oneString.filter(assertPredicate(isNumber, "Not all numbers")); // throws Error(""Not all numbers"");
363 * ```
364 */
365exports.assertPredicate = assertFn;
366/**
367 * Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test.
368 * @example
369 * ```
370 *
371 * var data = { foo: 1, bar: 2 };
372 *
373 * let keys = [ 'foo', 'bar' ]
374 * let values = keys.map(assertMap(key => data[key], "Key not found"));
375 * // values is [1, 2]
376 *
377 * let keys = [ 'foo', 'bar', 'baz' ]
378 * let values = keys.map(assertMap(key => data[key], "Key not found"));
379 * // throws Error("Key not found")
380 * ```
381 */
382exports.assertMap = assertFn;
383function assertFn(predicateOrMap, errMsg) {
384 if (errMsg === void 0) { errMsg = 'assert failure'; }
385 return function (obj) {
386 var result = predicateOrMap(obj);
387 if (!result) {
388 throw new Error(predicates_1.isFunction(errMsg) ? errMsg(obj) : errMsg);
389 }
390 return result;
391 };
392}
393exports.assertFn = assertFn;
394/**
395 * Like _.pairs: Given an object, returns an array of key/value pairs
396 *
397 * @example
398 * ```
399 *
400 * pairs({ foo: "FOO", bar: "BAR }) // [ [ "foo", "FOO" ], [ "bar": "BAR" ] ]
401 * ```
402 */
403exports.pairs = function (obj) { return Object.keys(obj).map(function (key) { return [key, obj[key]]; }); };
404/**
405 * Given two or more parallel arrays, returns an array of tuples where
406 * each tuple is composed of [ a[i], b[i], ... z[i] ]
407 *
408 * @example
409 * ```
410 *
411 * let foo = [ 0, 2, 4, 6 ];
412 * let bar = [ 1, 3, 5, 7 ];
413 * let baz = [ 10, 30, 50, 70 ];
414 * arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ]
415 * arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ]
416 * ```
417 */
418function arrayTuples() {
419 var args = [];
420 for (var _i = 0; _i < arguments.length; _i++) {
421 args[_i] = arguments[_i];
422 }
423 if (args.length === 0)
424 return [];
425 var maxArrayLen = args.reduce(function (min, arr) { return Math.min(arr.length, min); }, 9007199254740991); // aka 2^53 − 1 aka Number.MAX_SAFE_INTEGER
426 var result = [];
427 var _loop_1 = function (i) {
428 // This is a hot function
429 // Unroll when there are 1-4 arguments
430 switch (args.length) {
431 case 1:
432 result.push([args[0][i]]);
433 break;
434 case 2:
435 result.push([args[0][i], args[1][i]]);
436 break;
437 case 3:
438 result.push([args[0][i], args[1][i], args[2][i]]);
439 break;
440 case 4:
441 result.push([args[0][i], args[1][i], args[2][i], args[3][i]]);
442 break;
443 default:
444 result.push(args.map(function (array) { return array[i]; }));
445 break;
446 }
447 };
448 for (var i = 0; i < maxArrayLen; i++) {
449 _loop_1(i);
450 }
451 return result;
452}
453exports.arrayTuples = arrayTuples;
454/**
455 * Reduce function which builds an object from an array of [key, value] pairs.
456 *
457 * Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration.
458 *
459 * Each keyValueTuple should be an array with values [ key: string, value: any ]
460 *
461 * @example
462 * ```
463 *
464 * var pairs = [ ["fookey", "fooval"], ["barkey", "barval"] ]
465 *
466 * var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {})
467 * // pairsToObj == { fookey: "fooval", barkey: "barval" }
468 *
469 * // Or, more simply:
470 * var pairsToObj = pairs.reduce(applyPairs, {})
471 * // pairsToObj == { fookey: "fooval", barkey: "barval" }
472 * ```
473 */
474function applyPairs(memo, keyValTuple) {
475 var key, value;
476 if (predicates_1.isArray(keyValTuple))
477 key = keyValTuple[0], value = keyValTuple[1];
478 if (!predicates_1.isString(key))
479 throw new Error('invalid parameters to applyPairs');
480 memo[key] = value;
481 return memo;
482}
483exports.applyPairs = applyPairs;
484/** Get the last element of an array */
485function tail(arr) {
486 return (arr.length && arr[arr.length - 1]) || undefined;
487}
488exports.tail = tail;
489/**
490 * shallow copy from src to dest
491 */
492function copy(src, dest) {
493 if (dest)
494 Object.keys(dest).forEach(function (key) { return delete dest[key]; });
495 if (!dest)
496 dest = {};
497 return exports.extend(dest, src);
498}
499exports.copy = copy;
500/** Naive forEach implementation works with Objects or Arrays */
501function _forEach(obj, cb, _this) {
502 if (predicates_1.isArray(obj))
503 return obj.forEach(cb, _this);
504 Object.keys(obj).forEach(function (key) { return cb(obj[key], key); });
505}
506function _extend(toObj) {
507 for (var i = 1; i < arguments.length; i++) {
508 var obj = arguments[i];
509 if (!obj)
510 continue;
511 var keys = Object.keys(obj);
512 for (var j = 0; j < keys.length; j++) {
513 toObj[keys[j]] = obj[keys[j]];
514 }
515 }
516 return toObj;
517}
518exports._extend = _extend;
519function _equals(o1, o2) {
520 if (o1 === o2)
521 return true;
522 if (o1 === null || o2 === null)
523 return false;
524 if (o1 !== o1 && o2 !== o2)
525 return true; // NaN === NaN
526 var t1 = typeof o1, t2 = typeof o2;
527 if (t1 !== t2 || t1 !== 'object')
528 return false;
529 var tup = [o1, o2];
530 if (hof_1.all(predicates_1.isArray)(tup))
531 return _arraysEq(o1, o2);
532 if (hof_1.all(predicates_1.isDate)(tup))
533 return o1.getTime() === o2.getTime();
534 if (hof_1.all(predicates_1.isRegExp)(tup))
535 return o1.toString() === o2.toString();
536 if (hof_1.all(predicates_1.isFunction)(tup))
537 return true; // meh
538 var predicates = [predicates_1.isFunction, predicates_1.isArray, predicates_1.isDate, predicates_1.isRegExp];
539 if (predicates.map(hof_1.any).reduce(function (b, fn) { return b || !!fn(tup); }, false))
540 return false;
541 var keys = {};
542 // tslint:disable-next-line:forin
543 for (var key in o1) {
544 if (!_equals(o1[key], o2[key]))
545 return false;
546 keys[key] = true;
547 }
548 for (var key in o2) {
549 if (!keys[key])
550 return false;
551 }
552 return true;
553}
554function _arraysEq(a1, a2) {
555 if (a1.length !== a2.length)
556 return false;
557 return arrayTuples(a1, a2).reduce(function (b, t) { return b && _equals(t[0], t[1]); }, true);
558}
559// issue #2676
560exports.silenceUncaughtInPromise = function (promise) { return promise.catch(function (e) { return 0; }) && promise; };
561exports.silentRejection = function (error) { return exports.silenceUncaughtInPromise(coreservices_1.services.$q.reject(error)); };
562//# sourceMappingURL=common.js.map
\No newline at end of file