Debian Codegraph @

rhino/testsrc/org/mozilla/javascript/tests/commonjs/module/util.js

raw symbols SCIP
1
2 // Kris Kowal
3
4 // a decorator for functions that curry "polymorphically",
5 // that is, that return a function that can be tested
6 // against various objects if they're only "partially
7 // completed", or fewer arguments than needed are used.
8 //
9 // this enables the idioms:
10 // [1, 2, 3].every(lt(4)) eq true
11 // [1, 2, 3].map(add(1)) eq [2, 3, 4]
12 // [{}, {}, {}].forEach(set('a', 10))
13 //
14 exports.operator = function (name, length, block) {
15 var operator = function () {
16 var args = exports.array(arguments);
17 var completion = function (object) {
18 if (
19 typeof object == "object" &&
20 object !== null && // seriously? typeof null == "object"
21 name in object && // would throw if object === null
22 // not interested in literal objects:
23 !Object.prototype.hasOwnProperty.call(object, name)
24 )
25 return object[name].apply(object, args);
26 return block.apply(
27 this,
28 [object].concat(args)
29 );
30 };
31 if (arguments.length < length) {
32 // polymoprhic curry, delayed completion
33 return completion;
34 } else {
35 // immediate completion
36 return completion.call(this, args.shift());
37 }
38 };
39 operator.name = name;
40 operator.displayName = name;
41 operator.length = length;
42 operator.operator = block;
43 return operator;
44 };
45
46 exports.no = function (value) {
47 return value === null || value === undefined;
48 };
49
50 // object
51
52 exports.object = exports.operator('toObject', 1, function (object) {
53 var items = object;
54 if (!items.length)
55 items = exports.items(object);
56 var copy = {};
57 for (var i = 0; i < items.length; i++) {
58 var item = items[i];
59 var key = item[0];
60 var value = item[1];
61 copy[key] = value;
62 }
63 return copy;
64 });
65
66 exports.object.copy = function (object) {
67 var copy = {};
68 exports.object.keys(object).forEach(function (key) {
69 copy[key] = object[key];
70 });
71 return copy;
72 };
73
74 exports.object.deepCopy = function (object) {
75 var copy = {};
76 exports.object.keys(object).forEach(function (key) {
77 copy[key] = exports.deepCopy(object[key]);
78 });
79 return copy;
80 };
81
82 exports.object.eq = function (a, b, stack) {
83 return (
84 !exports.no(a) && !exports.no(b) &&
85 exports.array.eq(
86 exports.sort(exports.object.keys(a)),
87 exports.sort(exports.object.keys(b))
88 ) &&
89 exports.object.keys(a).every(function (key) {
90 return exports.eq(a[key], b[key], stack);
91 })
92 );
93 };
94
95 exports.object.len = function (object) {
96 return exports.object.keys(object).length;
97 };
98
99 exports.object.has = function (object, key) {
100 return Object.prototype.hasOwnProperty.call(object, key);
101 };
102
103 exports.object.keys = function (object) {
104 var keys = [];
105 for (var key in object) {
106 if (exports.object.has(object, key))
107 keys.push(key);
108 }
109 return keys;
110 };
111
112 exports.object.values = function (object) {
113 var values = [];
114 exports.object.keys(object).forEach(function (key) {
115 values.push(object[key]);
116 });
117 return values;
118 };
119
120 exports.object.items = function (object) {
121 var items = [];
122 exports.object.keys(object).forEach(function (key) {
123 items.push([key, object[key]]);
124 });
125 return items;
126 };
127
128 /**
129 * Updates an object with the properties from another object.
130 * This function is variadic requiring a minimum of two arguments.
131 * The first argument is the object to update. Remaining arguments
132 * are considered the sources for the update. If multiple sources
133 * contain values for the same property, the last one with that
134 * property in the arguments list wins.
135 *
136 * example usage:
137 * util.update({}, { hello: "world" }); // -> { hello: "world" }
138 * util.update({}, { hello: "world" }, { hello: "le monde" }); // -> { hello: "le monde" }
139 *
140 * @returns Updated object
141 * @type Object
142 *
143 */
144 exports.object.update = function () {
145 return variadicHelper(arguments, function(target, source) {
146 var key;
147 for (key in source) {
148 if (exports.object.has(source, key)) {
149 target[key] = source[key];
150 }
151 }
152 });
153 };
154
155 exports.object.deepUpdate = function (target, source) {
156 var key;
157 for (key in source) {
158 if(exports.object.has(source, key)) {
159 if(typeof source[key] == "object" && exports.object.has(target, key)) {
160 exports.object.deepUpdate(target[key], source[key]);
161 } else {
162 target[key] = source[key];
163 }
164 }
165 }
166 };
167
168 /**
169 * Updates an object with the properties of another object(s) if those
170 * properties are not already defined for the target object. First argument is
171 * the object to complete, the remaining arguments are considered sources to
172 * complete from. If multiple sources contain the same property, the value of
173 * the first source with that property will be the one inserted in to the
174 * target.
175 *
176 * example usage:
177 * util.complete({}, { hello: "world" }); // -> { hello: "world" }
178 * util.complete({ hello: "narwhal" }, { hello: "world" }); // -> { hello: "narwhal" }
179 * util.complete({}, { hello: "world" }, { hello: "le monde" }); // -> { hello: "world" }
180 *
181 * @returns Completed object
182 * @type Object
183 *
184 */
185 exports.object.complete = function () {
186 return variadicHelper(arguments, function(target, source) {
187 var key;
188 for (key in source) {
189 if (
190 exports.object.has(source, key) &&
191 !exports.object.has(target, key)
192 ) {
193 target[key] = source[key];
194 }
195 }
196 });
197 };
198
199 exports.object.deepComplete = function () {
200 return variadicHelper(arguments, function (target, source) {
201 var key;
202 for (key in source) {
203 if (
204 exports.object.has(source, key) &&
205 !exports.object.has(target, key)
206 ) {
207 target[key] = exports.deepCopy(source[key]);
208 }
209 }
210 });
211 };
212
213 exports.object.repr = function (object) {
214 return "{" +
215 exports.object.keys(object)
216 .map(function (key) {
217 return exports.enquote(key) + ": " +
218 exports.repr(object[key]);
219 }).join(", ") +
220 "}";
221 };
222
223 /**
224 * @param args Arguments list of the calling function
225 * First argument should be a callback that takes target and source parameters.
226 * Second argument should be target.
227 * Remaining arguments are treated a sources.
228 *
229 * @returns Target
230 * @type Object
231 */
232 var variadicHelper = function (args, callback) {
233 var sources = Array.prototype.slice.call(args);
234 var target = sources.shift();
235
236 sources.forEach(function(source) {
237 callback(target, source);
238 });
239
240 return target;
241 };
242
243 // array
244
245 exports.array = function (array) {
246 if (exports.no(array))
247 return [];
248 if (!exports.isArrayLike(array)) {
249 if (
250 array.toArray &&
251 !Object.prototype.hasOwnProperty.call(array, 'toArray')
252 ) {
253 return array.toArray();
254 } else if (
255 array.forEach &&
256 !Object.prototype.hasOwnProperty.call(array, 'forEach')
257 ) {
258 var results = [];
259 array.forEach(function (value) {
260 results.push(value);
261 });
262 return results;
263 } else if (typeof array === "string") {
264 return Array.prototype.slice.call(array);
265 } else {
266 return exports.items(array);
267 }
268 }
269 return Array.prototype.slice.call(array);
270 };
271
272 exports.array.coerce = function (array) {
273 if (!Array.isArray(array))
274 return exports.array(array);
275 return array;
276 };
277
278 exports.isArrayLike = function(object) {
279 return Array.isArray(object) || exports.isArguments(object);
280 };
281
282 // from http://code.google.com/p/google-caja/wiki/NiceNeighbor
283 // by "kangax"
284 //
285 // Mark Miller posted a solution that will work in ES5 compliant
286 // implementations, that may provide future insight:
287 // (http://groups.google.com/group/narwhaljs/msg/116097568bae41c6)
288 exports.isArguments = function (object) {
289 // ES5 reliable positive
290 if (Object.prototype.toString.call(object) == "[object Arguments]")
291 return true;
292 // for ES5, we will still need a way to distinguish false negatives
293 // from the following code (in ES5, it is possible to create
294 // an object that satisfies all of these constraints but is
295 // not an Arguments object).
296 // callee should exist
297 if (
298 !typeof object == "object" ||
299 !Object.prototype.hasOwnProperty.call(object, 'callee') ||
300 !object.callee ||
301 // It should be a Function object ([[Class]] === 'Function')
302 Object.prototype.toString.call(object.callee) !== '[object Function]' ||
303 typeof object.length != 'number'
304 )
305 return false;
306 for (var name in object) {
307 // both "callee" and "length" should be { DontEnum }
308 if (name === 'callee' || name === 'length') return false;
309 }
310 return true;
311 };
312
313 exports.array.copy = exports.array;
314
315 exports.array.deepCopy = function (array) {
316 return array.map(exports.deepCopy);
317 };
318
319 exports.array.len = function (array) {
320 return array.length;
321 };
322
323 exports.array.has = function (array, value) {
324 return Array.prototype.indexOf.call(array, value) >= 0;
325 };
326
327 exports.array.put = function (array, key, value) {
328 array.splice(key, 0, value);
329 return array;
330 };
331
332 exports.array.del = function (array, begin, end) {
333 array.splice(begin, end === undefined ? 1 : (end - begin));
334 return array;
335 };
336
337 exports.array.eq = function (a, b, stack) {
338 return exports.isArrayLike(b) &&
339 a.length == b.length &&
340 exports.zip(a, b).every(exports.apply(function (a, b) {
341 return exports.eq(a, b, stack);
342 }));
343 };
344
345 exports.array.lt = function (a, b) {
346 var length = Math.max(a.length, b.length);
347 for (var i = 0; i < length; i++)
348 if (!exports.eq(a[i], b[i]))
349 return exports.lt(a[i], b[i]);
350 return false;
351 };
352
353 exports.array.repr = function (array) {
354 return "[" + exports.map(array, exports.repr).join(', ') + "]";
355 };
356
357 exports.array.first = function (array) {
358 return array[0];
359 };
360
361 exports.array.last = function (array) {
362 return array[array.length - 1];
363 };
364
365 exports.apply = exports.operator('apply', 2, function (args, block) {
366 return block.apply(this, args);
367 });
368
369 exports.copy = exports.operator('copy', 1, function (object) {
370 if (exports.no(object))
371 return object;
372 if (exports.isArrayLike(object))
373 return exports.array.copy(object);
374 if (object instanceof Date)
375 return object;
376 if (typeof object == 'object')
377 return exports.object.copy(object);
378 return object;
379 });
380
381 exports.deepCopy = exports.operator('deepCopy', 1, function (object) {
382 if (exports.no(object))
383 return object;
384 if (exports.isArrayLike(object))
385 return exports.array.deepCopy(object);
386 if (typeof object == 'object')
387 return exports.object.deepCopy(object);
388 return object;
389 });
390
391 exports.repr = exports.operator('repr', 1, function (object) {
392 if (exports.no(object))
393 return String(object);
394 if (exports.isArrayLike(object))
395 return exports.array.repr(object);
396 if (typeof object == 'object')
397 return exports.object.repr(object);
398 if (typeof object == 'string')
399 return exports.enquote(object);
400 return object.toString();
401 });
402
403 exports.keys = exports.operator('keys', 1, function (object) {
404 if (exports.isArrayLike(object))
405 return exports.range(object.length);
406 else if (typeof object == 'object')
407 return exports.object.keys(object);
408 return [];
409 });
410
411 exports.values = exports.operator('values', 1, function (object) {
412 if (exports.isArrayLike(object))
413 return exports.array(object);
414 else if (typeof object == 'object')
415 return exports.object.values(object);
416 return [];
417 });
418
419 exports.items = exports.operator('items', 1, function (object) {
420 if (exports.isArrayLike(object) || typeof object == "string")
421 return exports.enumerate(object);
422 else if (typeof object == 'object')
423 return exports.object.items(object);
424 return [];
425 });
426
427 exports.len = exports.operator('len', 1, function (object) {
428 if (exports.isArrayLike(object))
429 return exports.array.len(object);
430 else if (typeof object == 'object')
431 return exports.object.len(object);
432 });
433
434 exports.has = exports.operator('has', 2, function (object, value) {
435 if (exports.isArrayLike(object))
436 return exports.array.has(object, value);
437 else if (typeof object == 'object')
438 return exports.object.has(object, value);
439 return false;
440 });
441
442 exports.get = exports.operator('get', 2, function (object, key, value) {
443 if (typeof object == "string") {
444 if (!typeof key == "number")
445 throw new Error("TypeError: String keys must be numbers");
446 if (!exports.has(exports.range(object.length), key)) {
447 if (arguments.length == 3)
448 return value;
449 throw new Error("KeyError: " + exports.repr(key));
450 }
451 return object.charAt(key);
452 }
453 if (typeof object == "object") {
454 if (!exports.object.has(object, key)) {
455 if (arguments.length == 3)
456 return value;
457 throw new Error("KeyError: " + exports.repr(key));
458 }
459 return object[key];
460 }
461 throw new Error("Object does not have keys: " + exports.repr(object));
462 });
463
464 exports.set = exports.operator('set', 3, function (object, key, value) {
465 object[key] = value;
466 return object;
467 });
468
469 exports.getset = exports.operator('getset', 3, function (object, key, value) {
470 if (!exports.has(object, key))
471 exports.set(object, key, value);
472 return exports.get(object, key);
473 });
474
475 exports.del = exports.operator('del', 2, function (object, begin, end) {
476 if (exports.isArrayLike(object))
477 return exports.array.del(object, begin, end);
478 delete object[begin];
479 return object;
480 });
481
482 exports.cut = exports.operator('cut', 2, function (object, key) {
483 var result = exports.get(object, key);
484 exports.del(object, key);
485 return result;
486 });
487
488 exports.put = exports.operator('put', 2, function (object, key, value) {
489 if (exports.isArrayLike(object))
490 return exports.array.put(object, key, value);
491 return exports.set(object, key, value);
492 });
493
494 exports.first = exports.operator('first', 1, function (object) {
495 return object[0];
496 });
497
498 exports.last = exports.operator('last', 1, function (object) {
499 return object[object.length - 1];
500 });
501
502 exports.update = exports.operator('update', 2, function () {
503 var args = Array.prototype.slice.call(arguments);
504 return exports.object.update.apply(this, args);
505 });
506
507 exports.deepUpdate = exports.operator('deepUpdate', 2, function (target, source) {
508 exports.object.deepUpdate(target, source);
509 });
510
511 exports.complete = exports.operator('complete', 2, function (target, source) {
512 var args = Array.prototype.slice.call(arguments);
513 return exports.object.complete.apply(this, args);
514 });
515
516 exports.deepComplete = exports.operator('deepComplete', 2, function (target, source) {
517 var args = Array.prototype.slice.call(arguments);
518 return exports.object.deepComplete.apply(this, args);
519 });
520
521 exports.remove = exports.operator('remove', 2, function (list, value) {
522 var index;
523 if ((index = list.indexOf(value))>-1)
524 list.splice(index,1);
525 return list;
526 });
527
528 // TODO insert
529 // TODO discard
530
531 exports.range = function () {
532 var start = 0, stop = 0, step = 1;
533 if (arguments.length == 1) {
534 stop = arguments[0];
535 } else {
536 start = arguments[0];
537 stop = arguments[1];
538 step = arguments[2] || 1;
539 }
540 var range = [];
541 for (var i = start; i < stop; i += step)
542 range.push(i);
543 return range;
544 };
545
546 exports.forEach = function (array, block) {
547 Array.prototype.forEach.call(
548 exports.array.coerce(array),
549 block
550 );
551 };
552
553 exports.forEachApply = function (array, block) {
554 Array.prototype.forEach.call(
555 exports.array.coerce(array),
556 exports.apply(block)
557 );
558 };
559
560 exports.map = function (array, block, context) {
561 return Array.prototype.map.call(
562 exports.array.coerce(array),
563 block,
564 context
565 );
566 };
567
568 exports.mapApply = function (array, block) {
569 return Array.prototype.map.call(
570 exports.array.coerce(array),
571 exports.apply(block)
572 );
573 };
574
575 exports.every = exports.operator('every', 2, function (array, block, context) {
576 return exports.all(exports.map(array, block, context));
577 });
578
579 exports.some = exports.operator('some', 2, function (array, block, context) {
580 return exports.any(exports.map(array, block, context));
581 });
582
583 exports.all = exports.operator('all', 1, function (array) {
584 array = exports.array.coerce(array);
585 for (var i = 0; i < array.length; i++)
586 if (!array[i])
587 return false;
588 return true;
589 });
590
591 exports.any = exports.operator('all', 1, function (array) {
592 array = exports.array.coerce(array);
593 for (var i = 0; i < array.length; i++)
594 if (array[i])
595 return true;
596 return false;
597 });
598
599 exports.reduce = exports.operator('reduce', 2, function (array, block, basis) {
600 array = exports.array.coerce(array);
601 return array.reduce.apply(array, arguments);
602 });
603
604 exports.reduceRight = exports.operator('reduceRight', 2, function (array, block, basis) {
605 array = exports.array.coerce(array);
606 return array.reduceRight.apply(array, arguments);
607 });
608
609 exports.zip = function () {
610 return exports.transpose(arguments);
611 };
612
613 exports.transpose = function (array) {
614 array = exports.array.coerce(array);
615 var transpose = [];
616 var length = Math.min.apply(this, exports.map(array, function (row) {
617 return row.length;
618 }));
619 for (var i = 0; i < array.length; i++) {
620 var row = array[i];
621 for (var j = 0; j < length; j++) {
622 var cell = row[j];
623 if (!transpose[j])
624 transpose[j] = [];
625 transpose[j][i] = cell;
626 }
627 }
628 return transpose;
629 };
630
631 exports.enumerate = function (array, start) {
632 array = exports.array.coerce(array);
633 if (exports.no(start))
634 start = 0;
635 return exports.zip(
636 exports.range(start, start + array.length),
637 array
638 );
639 };
640
641 // arithmetic, transitive, and logical operators
642
643 exports.is = function (a, b) {
644 // <Mark Miller>
645 if (a === b)
646 // 0 === -0, but they are not identical
647 return a !== 0 || 1/a === 1/b;
648 // NaN !== NaN, but they are identical.
649 // NaNs are the only non-reflexive value, i.e., if a !== a,
650 // then a is a NaN.
651 return a !== a && b !== b;
652 // </Mark Miller>
653 };
654
655 exports.eq = exports.operator('eq', 2, function (a, b, stack) {
656 if (!stack)
657 stack = [];
658 if (a === b)
659 return true;
660 if (typeof a !== typeof b)
661 return false;
662 if (exports.no(a))
663 return exports.no(b);
664 if (a instanceof Date)
665 return a.valueOf() === b.valueOf();
666 if (a instanceof RegExp)
667 return a.source === b.source &&
668 a.global === b.global &&
669 a.ignoreCase === b.ignoreCase &&
670 a.multiline === b.multiline;
671 if (typeof a === "function") {
672 var caller = stack[stack.length - 1];
673 // XXX what is this for? can it be axed?
674 // it comes from the "equiv" project code
675 return caller !== Object &&
676 typeof caller !== "undefined";
677 }
678 if (exports.isArrayLike(a))
679 return exports.array.eq(
680 a, b,
681 stack.concat([a.constructor])
682 );
683 if (typeof a === 'object')
684 return exports.object.eq(
685 a, b,
686 stack.concat([a.constructor])
687 );
688 return false;
689 });
690
691 exports.ne = exports.operator('ne', 2, function (a, b) {
692 return !exports.eq(a, b);
693 });
694
695 exports.lt = exports.operator('lt', 2, function (a, b) {
696 if (exports.no(a) != exports.no(b))
697 return exports.no(a) > exports.no(b);
698 if (exports.isArrayLike(a) && exports.isArrayLike(b))
699 return exports.array.lt(a, b);
700 return a < b;
701 });
702
703 exports.gt = exports.operator('gt', 2, function (a, b) {
704 return !(exports.lt(a, b) || exports.eq(a, b));
705 });
706
707 exports.le = exports.operator(2, 'le', function (a, b) {
708 return exports.lt(a, b) || exports.eq(a, b);
709 });
710
711 exports.ge = exports.operator(2, 'ge', function (a, b) {
712 return !exports.lt(a, b);
713 });
714
715 exports.mul = exports.operator(2, 'mul', function (a, b) {
716 if (typeof a == "string")
717 return exports.string.mul(a, b);
718 return a * b;
719 });
720
721 /*** by
722 returns a `comparator` that compares
723 values based on the values resultant from
724 a given `relation`.
725 accepts a `relation` and an optional comparator.
726
727 To sort a list of objects based on their
728 "a" key::
729
730 objects.sort(by(get("a")))
731
732 To get those in descending order::
733
734 objects.sort(by(get("a")), desc)
735
736 `by` returns a comparison function that also tracks
737 the arguments you used to construct it. This permits
738 `sort` and `sorted` to perform a Schwartzian transform
739 which can increase the performance of the sort
740 by a factor of 2.
741 */
742 exports.by = function (relation) {
743 var compare = arguments[1];
744 if (exports.no(compare))
745 compare = exports.compare;
746 var comparator = function (a, b) {
747 a = relation(a);
748 b = relation(b);
749 return compare(a, b);
750 };
751 comparator.by = relation;
752 comparator.compare = compare;
753 return comparator;
754 };
755
756 exports.compare = exports.operator(2, 'compare', function (a, b) {
757 if (exports.no(a) !== exports.no(b))
758 return exports.no(b) - exports.no(a);
759 if (typeof a === "number" && typeof b === "number")
760 return a - b;
761 return exports.eq(a, b) ? 0 : exports.lt(a, b) ? -1 : 1;
762 });
763
764 /*** sort
765 an in-place array sorter that uses a deep comparison
766 function by default (compare), and improves performance if
767 you provide a comparator returned by "by", using a
768 Schwartzian transform.
769 */
770 exports.sort = function (array, compare) {
771 if (exports.no(compare))
772 compare = exports.compare;
773 if (compare.by) {
774 /* schwartzian transform */
775 array.splice.apply(
776 array,
777 [0, array.length].concat(
778 array.map(function (value) {
779 return [compare.by(value), value];
780 }).sort(function (a, b) {
781 return compare.compare(a[0], b[0]);
782 }).map(function (pair) {
783 return pair[1];
784 })
785 )
786 );
787 } else {
788 array.sort(compare);
789 }
790 return array;
791 };
792
793 /*** sorted
794 returns a sorted copy of an array using a deep
795 comparison function by default (compare), and
796 improves performance if you provide a comparator
797 returned by "by", using a Schwartzian transform.
798 */
799 exports.sorted = function (array, compare) {
800 return exports.sort(exports.array.copy(array), compare);
801 };
802
803 exports.reverse = function (array) {
804 return Array.prototype.reverse.call(array);
805 };
806
807 exports.reversed = function (array) {
808 return exports.reverse(exports.array.copy(array));
809 };
810
811 exports.hash = exports.operator(1, 'hash', function (object) {
812 return '' + object;
813 });
814
815 exports.unique = exports.operator(1, 'unique', function (array, eq, hash) {
816 var visited = {};
817 if (!eq) eq = exports.eq;
818 if (!hash) hash = exports.hash;
819 return array.filter(function (value) {
820 var bucket = exports.getset(visited, hash(value), []);
821 var finds = bucket.filter(function (other) {
822 return eq(value, other);
823 });
824 if (!finds.length)
825 bucket.push(value);
826 return !finds.length;
827 });
828 });
829
830 // string
831
832 exports.string = exports.operator(1, 'toString', function (object) {
833 return '' + object;
834 });
835
836 exports.string.mul = function (string, n) {
837 return exports.range(n).map(function () {
838 return string;
839 }).join('');
840 };
841
842 /*** escape
843 escapes all characters of a string that are
844 special to JavaScript and many other languages.
845 Recognizes all of the relevant
846 control characters and formats all other
847 non-printable characters as Hex byte escape
848 sequences or Unicode escape sequences depending
849 on their size.
850
851 Pass ``true`` as an optional second argument and
852 ``escape`` produces valid contents for escaped
853 JSON strings, wherein non-printable-characters are
854 all escaped with the Unicode ``\u`` notation.
855 */
856 /* more Steve Levithan flagrence */
857 var escapeExpression = /[^ !#-[\]-~]/g;
858 /* from Doug Crockford's JSON library */
859 var escapePatterns = {
860 '\b': '\\b', '\t': '\\t',
861 '\n': '\\n', '\f': '\\f', '\r': '\\r',
862 '"' : '\\"', '\\': '\\\\'
863 };
864 exports.escape = function (value, strictJson) {
865 if (typeof value != "string")
866 throw new Error(
867 module.path +
868 "#escape: requires a string. got " +
869 exports.repr(value)
870 );
871 return value.replace(
872 escapeExpression,
873 function (match) {
874 if (escapePatterns[match])
875 return escapePatterns[match];
876 match = match.charCodeAt();
877 if (!strictJson && match < 256)
878 return "\\x" + exports.padBegin(match.toString(16), 2);
879 return '\\u' + exports.padBegin(match.toString(16), 4);
880 }
881 );
882 };
883
884 /*** enquote
885 transforms a string into a string literal, escaping
886 all characters of a string that are special to
887 JavaScript and and some other languages.
888
889 ``enquote`` uses double quotes to be JSON compatible.
890
891 Pass ``true`` as an optional second argument to
892 be strictly JSON compliant, wherein all
893 non-printable-characters are represented with
894 Unicode escape sequences.
895 */
896 exports.enquote = function (value, strictJson) {
897 return '"' + exports.escape(value, strictJson) + '"';
898 };
899
900 /*** expand
901 transforms tabs to an equivalent number of spaces.
902 */
903 // TODO special case for \r if it ever matters
904 exports.expand = function (str, tabLength) {
905 str = String(str);
906 tabLength = tabLength || 4;
907 var output = [],
908 tabLf = /[\t\n]/g,
909 lastLastIndex = 0,
910 lastLfIndex = 0,
911 charsAddedThisLine = 0,
912 tabOffset, match;
913 while (match = tabLf.exec(str)) {
914 if (match[0] == "\t") {
915 tabOffset = (
916 tabLength - 1 -
917 (
918 (match.index - lastLfIndex) +
919 charsAddedThisLine
920 ) % tabLength
921 );
922 charsAddedThisLine += tabOffset;
923 output.push(
924 str.slice(lastLastIndex, match.index) +
925 exports.mul(" ", tabOffset + 1)
926 );
927 } else if (match[0] === "\n") {
928 output.push(str.slice(lastLastIndex, tabLf.lastIndex));
929 lastLfIndex = tabLf.lastIndex;
930 charsAddedThisLine = 0;
931 }
932 lastLastIndex = tabLf.lastIndex;
933 }
934 return output.join("") + str.slice(lastLastIndex);
935 };
936
937 var trimBeginExpression = /^\s\s*/g;
938 exports.trimBegin = function (value) {
939 return String(value).replace(trimBeginExpression, "");
940 };
941
942 var trimEndExpression = /\s\s*$/g;
943 exports.trimEnd = function (value) {
944 return String(value).replace(trimEndExpression, "");
945 };
946
947 exports.trim = function (value) {
948 return String(value).replace(trimBeginExpression, "").replace(trimEndExpression, "");
949 };
950
951 /* generates padBegin and padEnd */
952 var augmentor = function (augment) {
953 return function (value, length, pad) {
954 if (exports.no(pad)) pad = '0';
955 if (exports.no(length)) length = 2;
956 value = String(value);
957 while (value.length < length) {
958 value = augment(value, pad);
959 }
960 return value;
961 };
962 };
963
964 /*** padBegin
965
966 accepts:
967 - a `String` or `Number` value
968 - a minimum length of the resultant `String`:
969 by default, 2
970 - a pad string: by default, ``'0'``.
971
972 returns a `String` of the value padded up to at least
973 the minimum length. adds the padding to the begining
974 side of the `String`.
975
976 */
977 exports.padBegin = augmentor(function (value, pad) {
978 return pad + value;
979 });
980
981 /*** padEnd
982
983 accepts:
984 - a `String` or `Number` value
985 - a minimum length of the resultant `String`:
986 by default, 2
987 - a pad string: by default, ``'0'``.
988
989 returns a `String` of the value padded up to at least
990 the minimum length. adds the padding to the end
991 side of the `String`.
992
993 */
994 exports.padEnd = augmentor(function (value, pad) {
995 return value + pad;
996 });
997
998 /*** splitName
999 splits a string into an array of words from an original
1000 string.
1001 */
1002 // thanks go to Steve Levithan for this regular expression
1003 // that, in addition to splitting any normal-form identifier
1004 // in any case convention, splits XMLHttpRequest into
1005 // "XML", "Http", and "Request"
1006 var splitNameExpression = /[a-z]+|[A-Z](?:[a-z]+|[A-Z]*(?![a-z]))|[.\d]+/g;
1007 exports.splitName = function (value) {
1008 return String(value).match(splitNameExpression);
1009 };
1010
1011 /*** joinName
1012 joins a list of words with a given delimiter
1013 between alphanumeric words.
1014 */
1015 exports.joinName = function (delimiter, parts) {
1016 if (exports.no(delimiter)) delimiter = '_';
1017 parts.unshift([]);
1018 return parts.reduce(function (parts, part) {
1019 if (
1020 part.match(/\d/) &&
1021 exports.len(parts) && parts[parts.length-1].match(/\d/)
1022 ) {
1023 return parts.concat([delimiter + part]);
1024 } else {
1025 return parts.concat([part]);
1026 }
1027 }).join('');
1028 };
1029
1030 /*** upper
1031 converts a name to ``UPPER CASE`` using
1032 a given delimiter between numeric words.
1033
1034 see:
1035 - `lower`
1036 - `camel`
1037 - `title`
1038
1039 */
1040 exports.upper = function (value, delimiter) {
1041 if (exports.no(delimiter))
1042 return value.toUpperCase();
1043 return exports.splitName(value).map(function (part) {
1044 return part.toUpperCase();
1045 }).join(delimiter);
1046 };
1047
1048 /*** lower
1049 converts a name to a ``lower case`` using
1050 a given delimiter between numeric words.
1051
1052 see:
1053 - `upper`
1054 - `camel`
1055 - `title`
1056
1057 */
1058 exports.lower = function (value, delimiter) {
1059 if (exports.no(delimiter))
1060 return String(value).toLowerCase();
1061 return exports.splitName(value).map(function (part) {
1062 return part.toLowerCase();
1063 }).join(delimiter);
1064 };
1065
1066 /*** camel
1067 converts a name to ``camel Case`` using
1068 a given delimiter between numeric words.
1069
1070 see:
1071 - `lower`
1072 - `upper`
1073 - `title`
1074
1075 */
1076 exports.camel = function (value, delimiter) {
1077 return exports.joinName(
1078 delimiter,
1079 exports.mapApply(
1080 exports.enumerate(exports.splitName(value)),
1081 function (n, part) {
1082 if (n) {
1083 return (
1084 part.substring(0, 1).toUpperCase() +
1085 part.substring(1).toLowerCase()
1086 );
1087 } else {
1088 return part.toLowerCase();
1089 }
1090 }
1091 )
1092 );
1093 };
1094
1095 /*** title
1096 converts a name to ``Title Case`` using
1097 a given delimiter between numeric words.
1098
1099 see:
1100 - `lower`
1101 - `upper`
1102 - `camel`
1103
1104 */
1105 exports.title = function (value, delimiter) {
1106 return exports.joinName(
1107 delimiter,
1108 exports.splitName(value).map(function (part) {
1109 return (
1110 part.substring(0, 1).toUpperCase() +
1111 part.substring(1).toLowerCase()
1112 );
1113 })
1114 );
1115 };