UNPKG

5.86 kBJavaScriptView Raw
1"use strict";
2/**
3 * Functions that manipulate strings
4 *
5 * Although these functions are exported, they are subject to change without notice.
6 *
7 * @packageDocumentation
8 */
9Object.defineProperty(exports, "__esModule", { value: true });
10exports.joinNeighborsR = exports.splitOnDelim = exports.trimHashVal = exports.splitEqual = exports.splitQuery = exports.splitHash = exports.stripLastPathElement = exports.hostRegex = exports.beforeAfterSubstr = exports.stringify = exports.fnToString = exports.functionToString = exports.kebobString = exports.padString = exports.maxLength = void 0;
11var predicates_1 = require("./predicates");
12var rejectFactory_1 = require("../transition/rejectFactory");
13var common_1 = require("./common");
14var hof_1 = require("./hof");
15/**
16 * Returns a string shortened to a maximum length
17 *
18 * If the string is already less than the `max` length, return the string.
19 * Else return the string, shortened to `max - 3` and append three dots ("...").
20 *
21 * @param max the maximum length of the string to return
22 * @param str the input string
23 */
24function maxLength(max, str) {
25 if (str.length <= max)
26 return str;
27 return str.substr(0, max - 3) + '...';
28}
29exports.maxLength = maxLength;
30/**
31 * Returns a string, with spaces added to the end, up to a desired str length
32 *
33 * If the string is already longer than the desired length, return the string.
34 * Else returns the string, with extra spaces on the end, such that it reaches `length` characters.
35 *
36 * @param length the desired length of the string to return
37 * @param str the input string
38 */
39function padString(length, str) {
40 while (str.length < length)
41 str += ' ';
42 return str;
43}
44exports.padString = padString;
45function kebobString(camelCase) {
46 return camelCase
47 .replace(/^([A-Z])/, function ($1) { return $1.toLowerCase(); }) // replace first char
48 .replace(/([A-Z])/g, function ($1) { return '-' + $1.toLowerCase(); }); // replace rest
49}
50exports.kebobString = kebobString;
51function functionToString(fn) {
52 var fnStr = fnToString(fn);
53 var namedFunctionMatch = fnStr.match(/^(function [^ ]+\([^)]*\))/);
54 var toStr = namedFunctionMatch ? namedFunctionMatch[1] : fnStr;
55 var fnName = fn['name'] || '';
56 if (fnName && toStr.match(/function \(/)) {
57 return 'function ' + fnName + toStr.substr(9);
58 }
59 return toStr;
60}
61exports.functionToString = functionToString;
62function fnToString(fn) {
63 var _fn = predicates_1.isArray(fn) ? fn.slice(-1)[0] : fn;
64 return (_fn && _fn.toString()) || 'undefined';
65}
66exports.fnToString = fnToString;
67function stringify(o) {
68 var seen = [];
69 var isRejection = rejectFactory_1.Rejection.isRejectionPromise;
70 var hasToString = function (obj) {
71 return predicates_1.isObject(obj) && !predicates_1.isArray(obj) && obj.constructor !== Object && predicates_1.isFunction(obj.toString);
72 };
73 var stringifyPattern = hof_1.pattern([
74 [predicates_1.isUndefined, hof_1.val('undefined')],
75 [predicates_1.isNull, hof_1.val('null')],
76 [predicates_1.isPromise, hof_1.val('[Promise]')],
77 [isRejection, function (x) { return x._transitionRejection.toString(); }],
78 [hasToString, function (x) { return x.toString(); }],
79 [predicates_1.isInjectable, functionToString],
80 [hof_1.val(true), common_1.identity],
81 ]);
82 function format(value) {
83 if (predicates_1.isObject(value)) {
84 if (seen.indexOf(value) !== -1)
85 return '[circular ref]';
86 seen.push(value);
87 }
88 return stringifyPattern(value);
89 }
90 if (predicates_1.isUndefined(o)) {
91 // Workaround for IE & Edge Spec incompatibility where replacer function would not be called when JSON.stringify
92 // is given `undefined` as value. To work around that, we simply detect `undefined` and bail out early by
93 // manually stringifying it.
94 return format(o);
95 }
96 return JSON.stringify(o, function (key, value) { return format(value); }).replace(/\\"/g, '"');
97}
98exports.stringify = stringify;
99/** Returns a function that splits a string on a character or substring */
100exports.beforeAfterSubstr = function (char) {
101 return function (str) {
102 if (!str)
103 return ['', ''];
104 var idx = str.indexOf(char);
105 if (idx === -1)
106 return [str, ''];
107 return [str.substr(0, idx), str.substr(idx + 1)];
108 };
109};
110exports.hostRegex = new RegExp('^(?:[a-z]+:)?//[^/]+/');
111exports.stripLastPathElement = function (str) { return str.replace(/\/[^/]*$/, ''); };
112exports.splitHash = exports.beforeAfterSubstr('#');
113exports.splitQuery = exports.beforeAfterSubstr('?');
114exports.splitEqual = exports.beforeAfterSubstr('=');
115exports.trimHashVal = function (str) { return (str ? str.replace(/^#/, '') : ''); };
116/**
117 * Splits on a delimiter, but returns the delimiters in the array
118 *
119 * #### Example:
120 * ```js
121 * var splitOnSlashes = splitOnDelim('/');
122 * splitOnSlashes("/foo"); // ["/", "foo"]
123 * splitOnSlashes("/foo/"); // ["/", "foo", "/"]
124 * ```
125 */
126function splitOnDelim(delim) {
127 var re = new RegExp('(' + delim + ')', 'g');
128 return function (str) { return str.split(re).filter(common_1.identity); };
129}
130exports.splitOnDelim = splitOnDelim;
131/**
132 * Reduce fn that joins neighboring strings
133 *
134 * Given an array of strings, returns a new array
135 * where all neighboring strings have been joined.
136 *
137 * #### Example:
138 * ```js
139 * let arr = ["foo", "bar", 1, "baz", "", "qux" ];
140 * arr.reduce(joinNeighborsR, []) // ["foobar", 1, "bazqux" ]
141 * ```
142 */
143function joinNeighborsR(acc, x) {
144 if (predicates_1.isString(common_1.tail(acc)) && predicates_1.isString(x))
145 return acc.slice(0, -1).concat(common_1.tail(acc) + x);
146 return common_1.pushR(acc, x);
147}
148exports.joinNeighborsR = joinNeighborsR;
149//# sourceMappingURL=strings.js.map
\No newline at end of file