1 | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AOlog = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
2 | (function (Buffer){
|
3 | 'use strict'
|
4 |
|
5 | var _ = require('lodash')
|
6 | var bloom = require('blomma')(1024, 1)
|
7 | var async = require('async')
|
8 | var pako = require('pako')
|
9 |
|
10 | module.exports = function (ipfs, BUCKET_SIZE) {
|
11 |
|
12 | var Ref = function (ref, filters, count) {
|
13 | return {
|
14 | type: 'Ref',
|
15 | filters: filters,
|
16 | ref: ref,
|
17 | count: count,
|
18 | children: 1,
|
19 | append: function (el, cb) {
|
20 | restore(this.ref.Hash, function (err, restored) {
|
21 | if (err) return cb(err)
|
22 | restored.append(el, function (err, res) {
|
23 | if (err) return cb(err)
|
24 | cb(null, res)
|
25 | })
|
26 | })
|
27 | },
|
28 | offset: function (ofs) {
|
29 | return [0, ofs]
|
30 | },
|
31 | getOffset: function () {
|
32 | return 0
|
33 | },
|
34 | getChild: function (idx, filter, cb) {
|
35 | var self = this
|
36 | restore(self.ref.Hash, function (err, res) {
|
37 | if (err) return cb(err)
|
38 | cb(null, { restored: res })
|
39 | })
|
40 | },
|
41 | persist: function (cb) {
|
42 | return cb(null, this.ref)
|
43 | }
|
44 | }
|
45 | }
|
46 |
|
47 | var Bucket = function (elements) {
|
48 | return {
|
49 | type: 'Bucket',
|
50 | elements: elements || [],
|
51 | count: elements.length,
|
52 | children: elements.length,
|
53 | filters: elementFilters(elements),
|
54 | append: function (el, cb) {
|
55 | if (this.elements.length === BUCKET_SIZE) {
|
56 | cb(null, { split: [ new Bucket(this.elements),
|
57 | new Bucket([el]) ] })
|
58 | } else {
|
59 | var newelements = _.clone(this.elements)
|
60 | newelements.push(el)
|
61 | cb(null, { value: new Bucket(newelements) })
|
62 | }
|
63 | },
|
64 | offset: function (ofs) {
|
65 | return [ofs, 0]
|
66 | },
|
67 | getOffset: function (idx) {
|
68 | return idx
|
69 | },
|
70 | getChild: function (idx, filter, cb) {
|
71 | var el = this.elements[idx]
|
72 | if (typeof el === 'undefined') return cb(null, { eof: true })
|
73 |
|
74 | if (matches(el, filter.words)) {
|
75 | return cb(null, { element: el })
|
76 | } else {
|
77 | return cb(null, { skip: true })
|
78 | }
|
79 | },
|
80 | persist: function (cb) {
|
81 | var self = this
|
82 |
|
83 | if (self.persisted) return cb(null, self.persisted)
|
84 |
|
85 | var buf = new Buffer(JSON.stringify({
|
86 | Data: JSON.stringify({
|
87 | type: 'Bucket',
|
88 | data: this
|
89 | }),
|
90 | Links: []
|
91 | }))
|
92 |
|
93 | ipfs.object.put(buf, 'json', function (err, put) {
|
94 | if (err) return cb(err)
|
95 |
|
96 | ipfs.object.stat(put.Hash, function (err, stat) {
|
97 | if (err) return cb(err)
|
98 | self.persisted = { Hash: put.Hash,
|
99 | Size: stat.CumulativeSize}
|
100 | cb(null, self.persisted)
|
101 | })
|
102 | })
|
103 | }
|
104 | }
|
105 | }
|
106 |
|
107 | var Branch = function (elements) {
|
108 | return {
|
109 | type: 'Branch',
|
110 | elements: elements,
|
111 | count: _.reduce(elements, function (a, b) {
|
112 | return a + b.count
|
113 | }, 0),
|
114 | children: elements.length,
|
115 | filters: combineFilters(this.elements),
|
116 | append: function (el, cb) {
|
117 | if (this.elements.length === BUCKET_SIZE) {
|
118 | cb(null, { split: [ new Branch(this.elements),
|
119 | new Branch([el]) ]})
|
120 | } else {
|
121 | var newelements = _.clone(this.elements)
|
122 | newelements.push(el)
|
123 | cb(null, { value: new Branch(newelements) })
|
124 | }
|
125 | },
|
126 | offset: function (ofs) {
|
127 | var idx = 0
|
128 | while (this.elements[(idx + 1)] && this.elements[idx].count <= ofs) {
|
129 | ofs -= this.elements[idx].count
|
130 | idx++
|
131 | }
|
132 | return [idx, ofs]
|
133 | },
|
134 | getOffset: function (idx) {
|
135 | var count = 0
|
136 | for (var i = 0 ; i < idx ; i++) {
|
137 | count += this.elements[i].count
|
138 | }
|
139 | return count
|
140 | },
|
141 | getChild: function (idx, filter, cb) {
|
142 | var element = this.elements[idx]
|
143 |
|
144 | if (element) {
|
145 | if (!subsetMatches(element.filters, filter.blooms)) {
|
146 | cb(null, { skip: true })
|
147 | } else {
|
148 | cb(null, { push: element })
|
149 | }
|
150 | } else {
|
151 | cb(null, { eof: true })
|
152 | }
|
153 | },
|
154 | persist: function (cb) {
|
155 | var self = this
|
156 |
|
157 | if (self.persisted) return cb(null, self.persisted)
|
158 |
|
159 | var filters = {}
|
160 | var counts = {}
|
161 | async.series(_.map(self.elements, function (element, idx) {
|
162 | var name = zeropad(idx)
|
163 | filters[name] = serializeFilters(self.elements[idx].filters)
|
164 | counts[name] = self.elements[idx].count
|
165 | return function (done) {
|
166 | element.persist(function (err, persisted) {
|
167 | if (err) return done(err)
|
168 | done(null, {
|
169 | Name: name,
|
170 | Hash: persisted.Hash,
|
171 | Size: persisted.Size
|
172 | })
|
173 | })
|
174 | }
|
175 | }), function (err, links) {
|
176 | if (err) return cb(err)
|
177 |
|
178 | var obj = {
|
179 | Data: JSON.stringify({
|
180 | type: self.type,
|
181 | counts: counts,
|
182 | filters: filters
|
183 | }),
|
184 | Links: links
|
185 | }
|
186 |
|
187 | var buf = new Buffer(JSON.stringify(obj))
|
188 | ipfs.object.put(buf, 'json', function (err, put) {
|
189 | if (err) return cb(err)
|
190 | ipfs.object.stat(put.Hash, function (err, stat) {
|
191 | if (err) return cb(err)
|
192 | self.persisted = { Hash: put.Hash,
|
193 | Size: stat.CumulativeSize }
|
194 | cb(null, self.persisted)
|
195 | })
|
196 | })
|
197 | })
|
198 | }
|
199 | }
|
200 | }
|
201 |
|
202 | var Finger = function (elements) {
|
203 | return {
|
204 | type: 'Finger',
|
205 | elements: elements,
|
206 | count: _.reduce(elements, function (a, b) {
|
207 | return a + b.count
|
208 | }, 0),
|
209 | children: 3,
|
210 | append: function (el, cb) {
|
211 |
|
212 | var self = this
|
213 | var tail = 2
|
214 | var newelements = _.clone(self.elements)
|
215 | elements[tail].append(el, function (err, res) {
|
216 | if (err) return cb(err)
|
217 | if (res.split) {
|
218 |
|
219 | newelements[2] = res.split[1]
|
220 | elements[1].append(res.split[0], function (err, pushres) {
|
221 | if (err) return cb(err)
|
222 | if (pushres.split) {
|
223 | newelements[1] = new Finger([ pushres.split[0],
|
224 | new Branch([]),
|
225 | pushres.split[1] ])
|
226 | } else {
|
227 | newelements[1] = pushres.value
|
228 | }
|
229 |
|
230 | cb(null, { value: new Finger(newelements)})
|
231 | })
|
232 | } else {
|
233 | newelements[2] = res.value
|
234 | cb(null, { value: new Finger(newelements)})
|
235 | }
|
236 | })
|
237 | },
|
238 | offset: function (ofs) {
|
239 | var idx = 0
|
240 | while (this.elements[(idx + 1)] && this.elements[idx].count <= ofs) {
|
241 | ofs -= this.elements[idx].count
|
242 | idx++
|
243 | }
|
244 | return [idx, ofs]
|
245 | },
|
246 | getOffset: function (idx) {
|
247 | var count = 0
|
248 | for (var i = 0 ; i < idx ; i++) {
|
249 | count += this.elements[i].count
|
250 | }
|
251 | return count
|
252 | },
|
253 | getChild: function (idx, filter, cb) {
|
254 | var element = this.elements[idx]
|
255 | if (element) {
|
256 | if (!subsetMatches(element.filters, filter.blooms)) {
|
257 | cb(null, { skip: true })
|
258 | } else {
|
259 | cb(null, { push: element })
|
260 | }
|
261 | } else {
|
262 | cb(null, { eof: true })
|
263 | }
|
264 | },
|
265 | persist: function (cb) {
|
266 | var self = this
|
267 |
|
268 | if (self.persisted) return cb(null, self.persisted)
|
269 |
|
270 | var filters = {}
|
271 | var counts = {}
|
272 | var parts = ['head', 'rest', 'tail']
|
273 | async.series(_.map(self.elements, function (element, idx) {
|
274 | var name = parts[idx]
|
275 | filters[name] = serializeFilters(self.elements[idx].filters)
|
276 | counts[name] = self.elements[idx].count
|
277 | return function (done) {
|
278 | self.elements[idx].persist(function (err, persisted) {
|
279 | if (err) return done(err)
|
280 | done(null, {
|
281 | Name: name,
|
282 | Hash: persisted.Hash,
|
283 | Size: persisted.Size
|
284 | })
|
285 | })
|
286 | }
|
287 | }), function (err, links) {
|
288 | if (err) return cb(err)
|
289 |
|
290 | var obj = {
|
291 | Data: JSON.stringify({
|
292 | type: 'Finger',
|
293 | filters: filters,
|
294 | counts: counts
|
295 | }),
|
296 | Links: links
|
297 | }
|
298 |
|
299 | var buf = new Buffer(JSON.stringify(obj))
|
300 |
|
301 | ipfs.object.put(buf, 'json', function (err, put) {
|
302 | if (err) return cb(err)
|
303 | ipfs.object.stat(put.Hash, function (err, stat) {
|
304 | if (err) return cb(err)
|
305 | self.persisted = { Hash: put.Hash,
|
306 | Size: stat.CumulativeSize }
|
307 | cb(null, self.persisted)
|
308 | })
|
309 | })
|
310 | })
|
311 | }
|
312 | }
|
313 | }
|
314 |
|
315 | var Root = function (ref) {
|
316 | if (!ref) ref = new Bucket([])
|
317 |
|
318 | return {
|
319 | type: 'Root',
|
320 | ref: ref,
|
321 | count: ref.count,
|
322 | append: function (el, cb) {
|
323 | this.ref.append(el, function (err, res) {
|
324 | if (err) return cb(err)
|
325 | if (res.split) {
|
326 | var newelements = []
|
327 | newelements[0] = res.split[0]
|
328 | newelements[1] = new Branch([])
|
329 | newelements[2] = res.split[1]
|
330 | cb(null, new Root(new Finger(newelements)))
|
331 | } else {
|
332 | cb(null, new Root(res.value))
|
333 | }
|
334 | })
|
335 | },
|
336 | iterator: function (opts) {
|
337 | return new Iterator(this.ref, opts)
|
338 | },
|
339 | persist: function (cb) {
|
340 | ref.persist(cb)
|
341 | },
|
342 | concat: function (items, cb) {
|
343 | var idx = 0
|
344 | var log = this
|
345 | async.forever(function (next) {
|
346 | log.append(items[idx++], function (err, res) {
|
347 | if (err) return cb(err)
|
348 | if (idx === items.length) return cb(null, res)
|
349 | log = res
|
350 | next()
|
351 | })
|
352 | })
|
353 | },
|
354 | get: function (idx, cb) {
|
355 | var self = this
|
356 | self.iterator({ offset: idx }).next(function (err, res) {
|
357 | if (err) return cb(err)
|
358 | cb(null, res)
|
359 | })
|
360 | }
|
361 | }
|
362 | }
|
363 |
|
364 | var Iterator = function (over, opts) {
|
365 | if (!opts) opts = {}
|
366 | var reverse = !!opts.reverse
|
367 | var fullfilter = makefilter(opts.filter)
|
368 | var def = reverse ? over.count - 1 : 0
|
369 | var offset = (typeof opts.offset !== 'undefined' ? opts.offset : def)
|
370 | var stack = null
|
371 |
|
372 | return {
|
373 | pushcount: 0,
|
374 | next: function (cb) {
|
375 | var self = this
|
376 |
|
377 |
|
378 | if (!stack) {
|
379 | stackFromOffset(over, offset, function (err, newstack) {
|
380 | if (err) return cb(err)
|
381 | stack = newstack
|
382 | self.next(cb)
|
383 | })
|
384 | return
|
385 | }
|
386 |
|
387 | if (!stack[0]) return cb(null, { eof: true })
|
388 |
|
389 | stack[0].obj.getChild(stack[0].idx, fullfilter, function (err, res) {
|
390 | if (err) return cb(err)
|
391 |
|
392 | if (res.eof) {
|
393 | stack.shift()
|
394 | if (!stack[0]) return cb(null, { eof: true })
|
395 | reverse ? stack[0].idx-- : stack[0].idx++
|
396 | self.next(cb)
|
397 | } else if (res.skip) {
|
398 | reverse ? stack[0].idx-- : stack[0].idx++
|
399 | self.next(cb)
|
400 | } else if (res.push) {
|
401 | self.pushcount++
|
402 | stack.unshift({ obj: res.push,
|
403 | idx: reverse ? res.push.children - 1 : 0 })
|
404 | self.next(cb)
|
405 | } else if (res.restored) {
|
406 | stack[0] = { obj: res.restored,
|
407 | idx: reverse ? res.restored.children - 1 : 0 }
|
408 | self.next(cb)
|
409 | } else if (typeof res.element !== 'undefined') {
|
410 | var index = offsetFromStack(stack)
|
411 |
|
412 | reverse ? stack[0].idx-- : stack[0].idx++
|
413 | cb(null, {
|
414 | element: res.element,
|
415 | index: index
|
416 | })
|
417 | } else {
|
418 | throw new Error('unhandled case, ' + JSON.stringify(res))
|
419 | }
|
420 | })
|
421 | },
|
422 | take: function (nr, cb) {
|
423 | var self = this
|
424 | var accum = []
|
425 | async.forever(function (next) {
|
426 | self.next(function (err, res) {
|
427 | if (err) return cb(err)
|
428 | if (res.eof) return cb(null, accum)
|
429 | if (!nr--) return cb(null, accum)
|
430 | accum.push(res)
|
431 | next()
|
432 | })
|
433 | })
|
434 | },
|
435 | all: function (cb) {
|
436 | this.take(Infinity, cb)
|
437 | }
|
438 | }
|
439 | }
|
440 |
|
441 | var offsetFromStack = function (stack) {
|
442 | return _.reduce(stack, function (acc, n) {
|
443 | return acc + n.obj.getOffset(n.idx)
|
444 | }, 0)
|
445 | }
|
446 |
|
447 | var stackFromOffset = function (over, offset, acc, cb) {
|
448 | if (!cb) {
|
449 | cb = acc
|
450 | acc = []
|
451 | }
|
452 |
|
453 | var idxrest = over.offset(offset)
|
454 |
|
455 | var idx = idxrest[0]
|
456 | var rest = idxrest[1]
|
457 |
|
458 | acc.unshift({ obj: over,
|
459 | idx: idx })
|
460 |
|
461 | over.getChild(idx, {}, function (err, res) {
|
462 | if (err) return cb(err)
|
463 | if (res.restored) {
|
464 | acc.shift()
|
465 | stackFromOffset(res.restored, rest, acc, cb)
|
466 | } else if (res.push) {
|
467 | stackFromOffset(res.push, rest, acc, cb)
|
468 | } else {
|
469 | cb(null, acc)
|
470 | }
|
471 | })
|
472 | }
|
473 |
|
474 | var elementFilters = function (elements) {
|
475 | var filter = {}
|
476 | _.forEach(elements, function (element) {
|
477 | _.forEach(element, function (value, key) {
|
478 | if (typeof value === 'string') {
|
479 | if (!filter[key]) filter[key] = bloom.empty()
|
480 | _.forEach(splitWords(value), function (word) {
|
481 | filter[key].add(word)
|
482 | })
|
483 | }
|
484 | })
|
485 | })
|
486 | return filter
|
487 | }
|
488 |
|
489 | var serializeFilters = function (filters) {
|
490 | var serialized = {}
|
491 | _.forEach(filters, function (value, key) {
|
492 | var compressed = new Buffer(pako.deflate(filters[key].buffer)).toString('base64')
|
493 | serialized[key] = compressed
|
494 | })
|
495 | return serialized
|
496 | }
|
497 |
|
498 | var deserializeFilters = function (filters) {
|
499 | var deserialized = {}
|
500 | _.forEach(filters, function (value, key) {
|
501 | var buffer = new Buffer(
|
502 | pako.inflate(new Buffer(filters[key], 'base64')),
|
503 | 'base64')
|
504 | deserialized[key] = bloom.fromBuffer(buffer)
|
505 | })
|
506 | return deserialized
|
507 | }
|
508 |
|
509 | var makefilter = function (filter) {
|
510 | if (!filter) {
|
511 | return {
|
512 | words: {},
|
513 | blooms: {}}
|
514 | }
|
515 |
|
516 | var blooms = {}
|
517 |
|
518 | _.forEach(filter, function (value, key) {
|
519 | blooms[key] = bloom.empty()
|
520 | _.forEach(splitWords(value), function (word) {
|
521 | blooms[key].add(word)
|
522 | })
|
523 | })
|
524 |
|
525 | return {words: filter,
|
526 | blooms: blooms}
|
527 | }
|
528 |
|
529 | var zeropad = function (nr) {
|
530 | var str = ('00' + nr)
|
531 | return str.substr(str.length - 3)
|
532 | }
|
533 |
|
534 | var combineFilters = function (tocombine) {
|
535 | var filters = {}
|
536 | _.forEach(tocombine, function (part) {
|
537 | _.forEach(part.filters, function (value, key) {
|
538 | if (!filters[key]) {
|
539 | filters[key] = value
|
540 | } else {
|
541 | filters[key] = bloom.merge(filters[key], value)
|
542 | }
|
543 | })
|
544 | })
|
545 | return filters
|
546 | }
|
547 |
|
548 | var splitWords = function (string) {
|
549 |
|
550 |
|
551 |
|
552 | return string.toLowerCase().split(/[^0-9a-z\u00C0-\u00ff\u00C0-\u024f#@_-]+/)
|
553 | }
|
554 |
|
555 | var matches = function (element, filter) {
|
556 | var matches = true
|
557 | _.forEach(filter, function (value, key) {
|
558 |
|
559 | var regexp = new RegExp('(?:^| )' + value + '(?:$| |[?!,.])', 'i')
|
560 | if (typeof element[key] !== 'string' ||
|
561 | !element[key].match(regexp)) {
|
562 | matches = false
|
563 | }
|
564 | })
|
565 |
|
566 | return matches
|
567 | }
|
568 |
|
569 | var subsetMatches = function (superset, subset) {
|
570 | var matches = true
|
571 | if (!superset || !Object.keys(superset).length) return true
|
572 |
|
573 | _.forEach(subset, function (value, key) {
|
574 | if (!superset[key] ||
|
575 | !superset[key].contains(value)) {
|
576 | matches = false
|
577 | }
|
578 | })
|
579 | return matches
|
580 | }
|
581 |
|
582 | var restore = function (hash, cb) {
|
583 | ipfs.object.get(hash, function (err, res) {
|
584 | if (err) return cb(err)
|
585 | var object = JSON.parse(res.Data)
|
586 |
|
587 | if (object.type === 'Bucket') {
|
588 | cb(null, new Bucket(object.data.elements))
|
589 | } else if (object.type === 'Branch') {
|
590 | cb(null, new Branch(_.map(res.Links, function (link, idx) {
|
591 | return new Ref({ Hash: link.Hash,
|
592 | Size: link.Size },
|
593 | deserializeFilters(object.filters[zeropad(idx)]),
|
594 | object.counts[zeropad(idx)])
|
595 | })))
|
596 | } else if (object.type === 'Finger') {
|
597 | var linkmap = {}
|
598 | _.forEach(res.Links, function (link) {
|
599 | linkmap[link.Name] = link
|
600 | })
|
601 |
|
602 | cb(null, new Finger([ new Ref({ Hash: linkmap.head.Hash,
|
603 | Size: linkmap.head.Size },
|
604 | deserializeFilters(object.filters.head),
|
605 | object.counts.head),
|
606 | new Ref({ Hash: linkmap.rest.Hash,
|
607 | Size: linkmap.rest.Size },
|
608 | deserializeFilters(object.filters.rest),
|
609 | object.counts.rest),
|
610 | new Ref({ Hash: linkmap.tail.Hash,
|
611 | Size: linkmap.tail.Size },
|
612 | deserializeFilters(object.filters.tail),
|
613 | object.counts.tail) ]))
|
614 | }
|
615 | })
|
616 | }
|
617 |
|
618 | return {
|
619 | empty: function () {
|
620 | return new Root()
|
621 | },
|
622 | restore: function (hash, cb) {
|
623 | restore(hash, function (err, res) {
|
624 | if (err) return cb(err)
|
625 | cb(null, new Root(res))
|
626 | })
|
627 | }
|
628 | }
|
629 | }
|
630 |
|
631 | }).call(this,require("buffer").Buffer)
|
632 | },{"async":2,"blomma":3,"buffer":5,"lodash":10,"pako":11}],2:[function(require,module,exports){
|
633 | (function (process,global){
|
634 |
|
635 |
|
636 |
|
637 |
|
638 |
|
639 |
|
640 |
|
641 | (function () {
|
642 |
|
643 | var async = {};
|
644 | function noop() {}
|
645 | function identity(v) {
|
646 | return v;
|
647 | }
|
648 | function toBool(v) {
|
649 | return !!v;
|
650 | }
|
651 | function notId(v) {
|
652 | return !v;
|
653 | }
|
654 |
|
655 |
|
656 | var previous_async;
|
657 |
|
658 |
|
659 |
|
660 |
|
661 | var root = typeof self === 'object' && self.self === self && self ||
|
662 | typeof global === 'object' && global.global === global && global ||
|
663 | this;
|
664 |
|
665 | if (root != null) {
|
666 | previous_async = root.async;
|
667 | }
|
668 |
|
669 | async.noConflict = function () {
|
670 | root.async = previous_async;
|
671 | return async;
|
672 | };
|
673 |
|
674 | function only_once(fn) {
|
675 | return function() {
|
676 | if (fn === null) throw new Error("Callback was already called.");
|
677 | fn.apply(this, arguments);
|
678 | fn = null;
|
679 | };
|
680 | }
|
681 |
|
682 | function _once(fn) {
|
683 | return function() {
|
684 | if (fn === null) return;
|
685 | fn.apply(this, arguments);
|
686 | fn = null;
|
687 | };
|
688 | }
|
689 |
|
690 |
|
691 |
|
692 | var _toString = Object.prototype.toString;
|
693 |
|
694 | var _isArray = Array.isArray || function (obj) {
|
695 | return _toString.call(obj) === '[object Array]';
|
696 | };
|
697 |
|
698 |
|
699 | var _isObject = function(obj) {
|
700 | var type = typeof obj;
|
701 | return type === 'function' || type === 'object' && !!obj;
|
702 | };
|
703 |
|
704 | function _isArrayLike(arr) {
|
705 | return _isArray(arr) || (
|
706 |
|
707 | typeof arr.length === "number" &&
|
708 | arr.length >= 0 &&
|
709 | arr.length % 1 === 0
|
710 | );
|
711 | }
|
712 |
|
713 | function _each(coll, iterator) {
|
714 | return _isArrayLike(coll) ?
|
715 | _arrayEach(coll, iterator) :
|
716 | _forEachOf(coll, iterator);
|
717 | }
|
718 |
|
719 | function _arrayEach(arr, iterator) {
|
720 | var index = -1,
|
721 | length = arr.length;
|
722 |
|
723 | while (++index < length) {
|
724 | iterator(arr[index], index, arr);
|
725 | }
|
726 | }
|
727 |
|
728 | function _map(arr, iterator) {
|
729 | var index = -1,
|
730 | length = arr.length,
|
731 | result = Array(length);
|
732 |
|
733 | while (++index < length) {
|
734 | result[index] = iterator(arr[index], index, arr);
|
735 | }
|
736 | return result;
|
737 | }
|
738 |
|
739 | function _range(count) {
|
740 | return _map(Array(count), function (v, i) { return i; });
|
741 | }
|
742 |
|
743 | function _reduce(arr, iterator, memo) {
|
744 | _arrayEach(arr, function (x, i, a) {
|
745 | memo = iterator(memo, x, i, a);
|
746 | });
|
747 | return memo;
|
748 | }
|
749 |
|
750 | function _forEachOf(object, iterator) {
|
751 | _arrayEach(_keys(object), function (key) {
|
752 | iterator(object[key], key);
|
753 | });
|
754 | }
|
755 |
|
756 | function _indexOf(arr, item) {
|
757 | for (var i = 0; i < arr.length; i++) {
|
758 | if (arr[i] === item) return i;
|
759 | }
|
760 | return -1;
|
761 | }
|
762 |
|
763 | var _keys = Object.keys || function (obj) {
|
764 | var keys = [];
|
765 | for (var k in obj) {
|
766 | if (obj.hasOwnProperty(k)) {
|
767 | keys.push(k);
|
768 | }
|
769 | }
|
770 | return keys;
|
771 | };
|
772 |
|
773 | function _keyIterator(coll) {
|
774 | var i = -1;
|
775 | var len;
|
776 | var keys;
|
777 | if (_isArrayLike(coll)) {
|
778 | len = coll.length;
|
779 | return function next() {
|
780 | i++;
|
781 | return i < len ? i : null;
|
782 | };
|
783 | } else {
|
784 | keys = _keys(coll);
|
785 | len = keys.length;
|
786 | return function next() {
|
787 | i++;
|
788 | return i < len ? keys[i] : null;
|
789 | };
|
790 | }
|
791 | }
|
792 |
|
793 |
|
794 |
|
795 |
|
796 | function _restParam(func, startIndex) {
|
797 | startIndex = startIndex == null ? func.length - 1 : +startIndex;
|
798 | return function() {
|
799 | var length = Math.max(arguments.length - startIndex, 0);
|
800 | var rest = Array(length);
|
801 | for (var index = 0; index < length; index++) {
|
802 | rest[index] = arguments[index + startIndex];
|
803 | }
|
804 | switch (startIndex) {
|
805 | case 0: return func.call(this, rest);
|
806 | case 1: return func.call(this, arguments[0], rest);
|
807 | }
|
808 |
|
809 |
|
810 |
|
811 |
|
812 |
|
813 |
|
814 |
|
815 | };
|
816 | }
|
817 |
|
818 | function _withoutIndex(iterator) {
|
819 | return function (value, index, callback) {
|
820 | return iterator(value, callback);
|
821 | };
|
822 | }
|
823 |
|
824 |
|
825 |
|
826 |
|
827 |
|
828 |
|
829 | var _setImmediate = typeof setImmediate === 'function' && setImmediate;
|
830 |
|
831 | var _delay = _setImmediate ? function(fn) {
|
832 |
|
833 | _setImmediate(fn);
|
834 | } : function(fn) {
|
835 | setTimeout(fn, 0);
|
836 | };
|
837 |
|
838 | if (typeof process === 'object' && typeof process.nextTick === 'function') {
|
839 | async.nextTick = process.nextTick;
|
840 | } else {
|
841 | async.nextTick = _delay;
|
842 | }
|
843 | async.setImmediate = _setImmediate ? _delay : async.nextTick;
|
844 |
|
845 |
|
846 | async.forEach =
|
847 | async.each = function (arr, iterator, callback) {
|
848 | return async.eachOf(arr, _withoutIndex(iterator), callback);
|
849 | };
|
850 |
|
851 | async.forEachSeries =
|
852 | async.eachSeries = function (arr, iterator, callback) {
|
853 | return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
|
854 | };
|
855 |
|
856 |
|
857 | async.forEachLimit =
|
858 | async.eachLimit = function (arr, limit, iterator, callback) {
|
859 | return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
|
860 | };
|
861 |
|
862 | async.forEachOf =
|
863 | async.eachOf = function (object, iterator, callback) {
|
864 | callback = _once(callback || noop);
|
865 | object = object || [];
|
866 | var size = _isArrayLike(object) ? object.length : _keys(object).length;
|
867 | var completed = 0;
|
868 | if (!size) {
|
869 | return callback(null);
|
870 | }
|
871 | _each(object, function (value, key) {
|
872 | iterator(object[key], key, only_once(done));
|
873 | });
|
874 | function done(err) {
|
875 | if (err) {
|
876 | callback(err);
|
877 | }
|
878 | else {
|
879 | completed += 1;
|
880 | if (completed >= size) {
|
881 | callback(null);
|
882 | }
|
883 | }
|
884 | }
|
885 | };
|
886 |
|
887 | async.forEachOfSeries =
|
888 | async.eachOfSeries = function (obj, iterator, callback) {
|
889 | callback = _once(callback || noop);
|
890 | obj = obj || [];
|
891 | var nextKey = _keyIterator(obj);
|
892 | var key = nextKey();
|
893 | function iterate() {
|
894 | var sync = true;
|
895 | if (key === null) {
|
896 | return callback(null);
|
897 | }
|
898 | iterator(obj[key], key, only_once(function (err) {
|
899 | if (err) {
|
900 | callback(err);
|
901 | }
|
902 | else {
|
903 | key = nextKey();
|
904 | if (key === null) {
|
905 | return callback(null);
|
906 | } else {
|
907 | if (sync) {
|
908 | async.nextTick(iterate);
|
909 | } else {
|
910 | iterate();
|
911 | }
|
912 | }
|
913 | }
|
914 | }));
|
915 | sync = false;
|
916 | }
|
917 | iterate();
|
918 | };
|
919 |
|
920 |
|
921 |
|
922 | async.forEachOfLimit =
|
923 | async.eachOfLimit = function (obj, limit, iterator, callback) {
|
924 | _eachOfLimit(limit)(obj, iterator, callback);
|
925 | };
|
926 |
|
927 | function _eachOfLimit(limit) {
|
928 |
|
929 | return function (obj, iterator, callback) {
|
930 | callback = _once(callback || noop);
|
931 | obj = obj || [];
|
932 | var nextKey = _keyIterator(obj);
|
933 | if (limit <= 0) {
|
934 | return callback(null);
|
935 | }
|
936 | var done = false;
|
937 | var running = 0;
|
938 | var errored = false;
|
939 |
|
940 | (function replenish () {
|
941 | if (done && running <= 0) {
|
942 | return callback(null);
|
943 | }
|
944 |
|
945 | while (running < limit && !errored) {
|
946 | var key = nextKey();
|
947 | if (key === null) {
|
948 | done = true;
|
949 | if (running <= 0) {
|
950 | callback(null);
|
951 | }
|
952 | return;
|
953 | }
|
954 | running += 1;
|
955 | iterator(obj[key], key, only_once(function (err) {
|
956 | running -= 1;
|
957 | if (err) {
|
958 | callback(err);
|
959 | errored = true;
|
960 | }
|
961 | else {
|
962 | replenish();
|
963 | }
|
964 | }));
|
965 | }
|
966 | })();
|
967 | };
|
968 | }
|
969 |
|
970 |
|
971 | function doParallel(fn) {
|
972 | return function (obj, iterator, callback) {
|
973 | return fn(async.eachOf, obj, iterator, callback);
|
974 | };
|
975 | }
|
976 | function doParallelLimit(fn) {
|
977 | return function (obj, limit, iterator, callback) {
|
978 | return fn(_eachOfLimit(limit), obj, iterator, callback);
|
979 | };
|
980 | }
|
981 | function doSeries(fn) {
|
982 | return function (obj, iterator, callback) {
|
983 | return fn(async.eachOfSeries, obj, iterator, callback);
|
984 | };
|
985 | }
|
986 |
|
987 | function _asyncMap(eachfn, arr, iterator, callback) {
|
988 | callback = _once(callback || noop);
|
989 | var results = [];
|
990 | eachfn(arr, function (value, index, callback) {
|
991 | iterator(value, function (err, v) {
|
992 | results[index] = v;
|
993 | callback(err);
|
994 | });
|
995 | }, function (err) {
|
996 | callback(err, results);
|
997 | });
|
998 | }
|
999 |
|
1000 | async.map = doParallel(_asyncMap);
|
1001 | async.mapSeries = doSeries(_asyncMap);
|
1002 | async.mapLimit = doParallelLimit(_asyncMap);
|
1003 |
|
1004 |
|
1005 |
|
1006 | async.inject =
|
1007 | async.foldl =
|
1008 | async.reduce = function (arr, memo, iterator, callback) {
|
1009 | async.eachOfSeries(arr, function (x, i, callback) {
|
1010 | iterator(memo, x, function (err, v) {
|
1011 | memo = v;
|
1012 | callback(err);
|
1013 | });
|
1014 | }, function (err) {
|
1015 | callback(err || null, memo);
|
1016 | });
|
1017 | };
|
1018 |
|
1019 | async.foldr =
|
1020 | async.reduceRight = function (arr, memo, iterator, callback) {
|
1021 | var reversed = _map(arr, identity).reverse();
|
1022 | async.reduce(reversed, memo, iterator, callback);
|
1023 | };
|
1024 |
|
1025 | function _filter(eachfn, arr, iterator, callback) {
|
1026 | var results = [];
|
1027 | eachfn(arr, function (x, index, callback) {
|
1028 | iterator(x, function (v) {
|
1029 | if (v) {
|
1030 | results.push({index: index, value: x});
|
1031 | }
|
1032 | callback();
|
1033 | });
|
1034 | }, function () {
|
1035 | callback(_map(results.sort(function (a, b) {
|
1036 | return a.index - b.index;
|
1037 | }), function (x) {
|
1038 | return x.value;
|
1039 | }));
|
1040 | });
|
1041 | }
|
1042 |
|
1043 | async.select =
|
1044 | async.filter = doParallel(_filter);
|
1045 |
|
1046 | async.selectLimit =
|
1047 | async.filterLimit = doParallelLimit(_filter);
|
1048 |
|
1049 | async.selectSeries =
|
1050 | async.filterSeries = doSeries(_filter);
|
1051 |
|
1052 | function _reject(eachfn, arr, iterator, callback) {
|
1053 | _filter(eachfn, arr, function(value, cb) {
|
1054 | iterator(value, function(v) {
|
1055 | cb(!v);
|
1056 | });
|
1057 | }, callback);
|
1058 | }
|
1059 | async.reject = doParallel(_reject);
|
1060 | async.rejectLimit = doParallelLimit(_reject);
|
1061 | async.rejectSeries = doSeries(_reject);
|
1062 |
|
1063 | function _createTester(eachfn, check, getResult) {
|
1064 | return function(arr, limit, iterator, cb) {
|
1065 | function done() {
|
1066 | if (cb) cb(getResult(false, void 0));
|
1067 | }
|
1068 | function iteratee(x, _, callback) {
|
1069 | if (!cb) return callback();
|
1070 | iterator(x, function (v) {
|
1071 | if (cb && check(v)) {
|
1072 | cb(getResult(true, x));
|
1073 | cb = iterator = false;
|
1074 | }
|
1075 | callback();
|
1076 | });
|
1077 | }
|
1078 | if (arguments.length > 3) {
|
1079 | eachfn(arr, limit, iteratee, done);
|
1080 | } else {
|
1081 | cb = iterator;
|
1082 | iterator = limit;
|
1083 | eachfn(arr, iteratee, done);
|
1084 | }
|
1085 | };
|
1086 | }
|
1087 |
|
1088 | async.any =
|
1089 | async.some = _createTester(async.eachOf, toBool, identity);
|
1090 |
|
1091 | async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
|
1092 |
|
1093 | async.all =
|
1094 | async.every = _createTester(async.eachOf, notId, notId);
|
1095 |
|
1096 | async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
|
1097 |
|
1098 | function _findGetResult(v, x) {
|
1099 | return x;
|
1100 | }
|
1101 | async.detect = _createTester(async.eachOf, identity, _findGetResult);
|
1102 | async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
|
1103 | async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
|
1104 |
|
1105 | async.sortBy = function (arr, iterator, callback) {
|
1106 | async.map(arr, function (x, callback) {
|
1107 | iterator(x, function (err, criteria) {
|
1108 | if (err) {
|
1109 | callback(err);
|
1110 | }
|
1111 | else {
|
1112 | callback(null, {value: x, criteria: criteria});
|
1113 | }
|
1114 | });
|
1115 | }, function (err, results) {
|
1116 | if (err) {
|
1117 | return callback(err);
|
1118 | }
|
1119 | else {
|
1120 | callback(null, _map(results.sort(comparator), function (x) {
|
1121 | return x.value;
|
1122 | }));
|
1123 | }
|
1124 |
|
1125 | });
|
1126 |
|
1127 | function comparator(left, right) {
|
1128 | var a = left.criteria, b = right.criteria;
|
1129 | return a < b ? -1 : a > b ? 1 : 0;
|
1130 | }
|
1131 | };
|
1132 |
|
1133 | async.auto = function (tasks, callback) {
|
1134 | callback = _once(callback || noop);
|
1135 | var keys = _keys(tasks);
|
1136 | var remainingTasks = keys.length;
|
1137 | if (!remainingTasks) {
|
1138 | return callback(null);
|
1139 | }
|
1140 |
|
1141 | var results = {};
|
1142 |
|
1143 | var listeners = [];
|
1144 | function addListener(fn) {
|
1145 | listeners.unshift(fn);
|
1146 | }
|
1147 | function removeListener(fn) {
|
1148 | var idx = _indexOf(listeners, fn);
|
1149 | if (idx >= 0) listeners.splice(idx, 1);
|
1150 | }
|
1151 | function taskComplete() {
|
1152 | remainingTasks--;
|
1153 | _arrayEach(listeners.slice(0), function (fn) {
|
1154 | fn();
|
1155 | });
|
1156 | }
|
1157 |
|
1158 | addListener(function () {
|
1159 | if (!remainingTasks) {
|
1160 | callback(null, results);
|
1161 | }
|
1162 | });
|
1163 |
|
1164 | _arrayEach(keys, function (k) {
|
1165 | var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
|
1166 | var taskCallback = _restParam(function(err, args) {
|
1167 | if (args.length <= 1) {
|
1168 | args = args[0];
|
1169 | }
|
1170 | if (err) {
|
1171 | var safeResults = {};
|
1172 | _forEachOf(results, function(val, rkey) {
|
1173 | safeResults[rkey] = val;
|
1174 | });
|
1175 | safeResults[k] = args;
|
1176 | callback(err, safeResults);
|
1177 | }
|
1178 | else {
|
1179 | results[k] = args;
|
1180 | async.setImmediate(taskComplete);
|
1181 | }
|
1182 | });
|
1183 | var requires = task.slice(0, task.length - 1);
|
1184 |
|
1185 | var len = requires.length;
|
1186 | var dep;
|
1187 | while (len--) {
|
1188 | if (!(dep = tasks[requires[len]])) {
|
1189 | throw new Error('Has inexistant dependency');
|
1190 | }
|
1191 | if (_isArray(dep) && _indexOf(dep, k) >= 0) {
|
1192 | throw new Error('Has cyclic dependencies');
|
1193 | }
|
1194 | }
|
1195 | function ready() {
|
1196 | return _reduce(requires, function (a, x) {
|
1197 | return (a && results.hasOwnProperty(x));
|
1198 | }, true) && !results.hasOwnProperty(k);
|
1199 | }
|
1200 | if (ready()) {
|
1201 | task[task.length - 1](taskCallback, results);
|
1202 | }
|
1203 | else {
|
1204 | addListener(listener);
|
1205 | }
|
1206 | function listener() {
|
1207 | if (ready()) {
|
1208 | removeListener(listener);
|
1209 | task[task.length - 1](taskCallback, results);
|
1210 | }
|
1211 | }
|
1212 | });
|
1213 | };
|
1214 |
|
1215 |
|
1216 |
|
1217 | async.retry = function(times, task, callback) {
|
1218 | var DEFAULT_TIMES = 5;
|
1219 | var DEFAULT_INTERVAL = 0;
|
1220 |
|
1221 | var attempts = [];
|
1222 |
|
1223 | var opts = {
|
1224 | times: DEFAULT_TIMES,
|
1225 | interval: DEFAULT_INTERVAL
|
1226 | };
|
1227 |
|
1228 | function parseTimes(acc, t){
|
1229 | if(typeof t === 'number'){
|
1230 | acc.times = parseInt(t, 10) || DEFAULT_TIMES;
|
1231 | } else if(typeof t === 'object'){
|
1232 | acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
|
1233 | acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
|
1234 | } else {
|
1235 | throw new Error('Unsupported argument type for \'times\': ' + typeof t);
|
1236 | }
|
1237 | }
|
1238 |
|
1239 | var length = arguments.length;
|
1240 | if (length < 1 || length > 3) {
|
1241 | throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
|
1242 | } else if (length <= 2 && typeof times === 'function') {
|
1243 | callback = task;
|
1244 | task = times;
|
1245 | }
|
1246 | if (typeof times !== 'function') {
|
1247 | parseTimes(opts, times);
|
1248 | }
|
1249 | opts.callback = callback;
|
1250 | opts.task = task;
|
1251 |
|
1252 | function wrappedTask(wrappedCallback, wrappedResults) {
|
1253 | function retryAttempt(task, finalAttempt) {
|
1254 | return function(seriesCallback) {
|
1255 | task(function(err, result){
|
1256 | seriesCallback(!err || finalAttempt, {err: err, result: result});
|
1257 | }, wrappedResults);
|
1258 | };
|
1259 | }
|
1260 |
|
1261 | function retryInterval(interval){
|
1262 | return function(seriesCallback){
|
1263 | setTimeout(function(){
|
1264 | seriesCallback(null);
|
1265 | }, interval);
|
1266 | };
|
1267 | }
|
1268 |
|
1269 | while (opts.times) {
|
1270 |
|
1271 | var finalAttempt = !(opts.times-=1);
|
1272 | attempts.push(retryAttempt(opts.task, finalAttempt));
|
1273 | if(!finalAttempt && opts.interval > 0){
|
1274 | attempts.push(retryInterval(opts.interval));
|
1275 | }
|
1276 | }
|
1277 |
|
1278 | async.series(attempts, function(done, data){
|
1279 | data = data[data.length - 1];
|
1280 | (wrappedCallback || opts.callback)(data.err, data.result);
|
1281 | });
|
1282 | }
|
1283 |
|
1284 |
|
1285 | return opts.callback ? wrappedTask() : wrappedTask;
|
1286 | };
|
1287 |
|
1288 | async.waterfall = function (tasks, callback) {
|
1289 | callback = _once(callback || noop);
|
1290 | if (!_isArray(tasks)) {
|
1291 | var err = new Error('First argument to waterfall must be an array of functions');
|
1292 | return callback(err);
|
1293 | }
|
1294 | if (!tasks.length) {
|
1295 | return callback();
|
1296 | }
|
1297 | function wrapIterator(iterator) {
|
1298 | return _restParam(function (err, args) {
|
1299 | if (err) {
|
1300 | callback.apply(null, [err].concat(args));
|
1301 | }
|
1302 | else {
|
1303 | var next = iterator.next();
|
1304 | if (next) {
|
1305 | args.push(wrapIterator(next));
|
1306 | }
|
1307 | else {
|
1308 | args.push(callback);
|
1309 | }
|
1310 | ensureAsync(iterator).apply(null, args);
|
1311 | }
|
1312 | });
|
1313 | }
|
1314 | wrapIterator(async.iterator(tasks))();
|
1315 | };
|
1316 |
|
1317 | function _parallel(eachfn, tasks, callback) {
|
1318 | callback = callback || noop;
|
1319 | var results = _isArrayLike(tasks) ? [] : {};
|
1320 |
|
1321 | eachfn(tasks, function (task, key, callback) {
|
1322 | task(_restParam(function (err, args) {
|
1323 | if (args.length <= 1) {
|
1324 | args = args[0];
|
1325 | }
|
1326 | results[key] = args;
|
1327 | callback(err);
|
1328 | }));
|
1329 | }, function (err) {
|
1330 | callback(err, results);
|
1331 | });
|
1332 | }
|
1333 |
|
1334 | async.parallel = function (tasks, callback) {
|
1335 | _parallel(async.eachOf, tasks, callback);
|
1336 | };
|
1337 |
|
1338 | async.parallelLimit = function(tasks, limit, callback) {
|
1339 | _parallel(_eachOfLimit(limit), tasks, callback);
|
1340 | };
|
1341 |
|
1342 | async.series = function(tasks, callback) {
|
1343 | _parallel(async.eachOfSeries, tasks, callback);
|
1344 | };
|
1345 |
|
1346 | async.iterator = function (tasks) {
|
1347 | function makeCallback(index) {
|
1348 | function fn() {
|
1349 | if (tasks.length) {
|
1350 | tasks[index].apply(null, arguments);
|
1351 | }
|
1352 | return fn.next();
|
1353 | }
|
1354 | fn.next = function () {
|
1355 | return (index < tasks.length - 1) ? makeCallback(index + 1): null;
|
1356 | };
|
1357 | return fn;
|
1358 | }
|
1359 | return makeCallback(0);
|
1360 | };
|
1361 |
|
1362 | async.apply = _restParam(function (fn, args) {
|
1363 | return _restParam(function (callArgs) {
|
1364 | return fn.apply(
|
1365 | null, args.concat(callArgs)
|
1366 | );
|
1367 | });
|
1368 | });
|
1369 |
|
1370 | function _concat(eachfn, arr, fn, callback) {
|
1371 | var result = [];
|
1372 | eachfn(arr, function (x, index, cb) {
|
1373 | fn(x, function (err, y) {
|
1374 | result = result.concat(y || []);
|
1375 | cb(err);
|
1376 | });
|
1377 | }, function (err) {
|
1378 | callback(err, result);
|
1379 | });
|
1380 | }
|
1381 | async.concat = doParallel(_concat);
|
1382 | async.concatSeries = doSeries(_concat);
|
1383 |
|
1384 | async.whilst = function (test, iterator, callback) {
|
1385 | callback = callback || noop;
|
1386 | if (test()) {
|
1387 | var next = _restParam(function(err, args) {
|
1388 | if (err) {
|
1389 | callback(err);
|
1390 | } else if (test.apply(this, args)) {
|
1391 | iterator(next);
|
1392 | } else {
|
1393 | callback(null);
|
1394 | }
|
1395 | });
|
1396 | iterator(next);
|
1397 | } else {
|
1398 | callback(null);
|
1399 | }
|
1400 | };
|
1401 |
|
1402 | async.doWhilst = function (iterator, test, callback) {
|
1403 | var calls = 0;
|
1404 | return async.whilst(function() {
|
1405 | return ++calls <= 1 || test.apply(this, arguments);
|
1406 | }, iterator, callback);
|
1407 | };
|
1408 |
|
1409 | async.until = function (test, iterator, callback) {
|
1410 | return async.whilst(function() {
|
1411 | return !test.apply(this, arguments);
|
1412 | }, iterator, callback);
|
1413 | };
|
1414 |
|
1415 | async.doUntil = function (iterator, test, callback) {
|
1416 | return async.doWhilst(iterator, function() {
|
1417 | return !test.apply(this, arguments);
|
1418 | }, callback);
|
1419 | };
|
1420 |
|
1421 | async.during = function (test, iterator, callback) {
|
1422 | callback = callback || noop;
|
1423 |
|
1424 | var next = _restParam(function(err, args) {
|
1425 | if (err) {
|
1426 | callback(err);
|
1427 | } else {
|
1428 | args.push(check);
|
1429 | test.apply(this, args);
|
1430 | }
|
1431 | });
|
1432 |
|
1433 | var check = function(err, truth) {
|
1434 | if (err) {
|
1435 | callback(err);
|
1436 | } else if (truth) {
|
1437 | iterator(next);
|
1438 | } else {
|
1439 | callback(null);
|
1440 | }
|
1441 | };
|
1442 |
|
1443 | test(check);
|
1444 | };
|
1445 |
|
1446 | async.doDuring = function (iterator, test, callback) {
|
1447 | var calls = 0;
|
1448 | async.during(function(next) {
|
1449 | if (calls++ < 1) {
|
1450 | next(null, true);
|
1451 | } else {
|
1452 | test.apply(this, arguments);
|
1453 | }
|
1454 | }, iterator, callback);
|
1455 | };
|
1456 |
|
1457 | function _queue(worker, concurrency, payload) {
|
1458 | if (concurrency == null) {
|
1459 | concurrency = 1;
|
1460 | }
|
1461 | else if(concurrency === 0) {
|
1462 | throw new Error('Concurrency must not be zero');
|
1463 | }
|
1464 | function _insert(q, data, pos, callback) {
|
1465 | if (callback != null && typeof callback !== "function") {
|
1466 | throw new Error("task callback must be a function");
|
1467 | }
|
1468 | q.started = true;
|
1469 | if (!_isArray(data)) {
|
1470 | data = [data];
|
1471 | }
|
1472 | if(data.length === 0 && q.idle()) {
|
1473 | // call drain immediately if there are no tasks
|
1474 | return async.setImmediate(function() {
|
1475 | q.drain();
|
1476 | });
|
1477 | }
|
1478 | _arrayEach(data, function(task) {
|
1479 | var item = {
|
1480 | data: task,
|
1481 | callback: callback || noop
|
1482 | };
|
1483 |
|
1484 | if (pos) {
|
1485 | q.tasks.unshift(item);
|
1486 | } else {
|
1487 | q.tasks.push(item);
|
1488 | }
|
1489 |
|
1490 | if (q.tasks.length === q.concurrency) {
|
1491 | q.saturated();
|
1492 | }
|
1493 | });
|
1494 | async.setImmediate(q.process);
|
1495 | }
|
1496 | function _next(q, tasks) {
|
1497 | return function(){
|
1498 | workers -= 1;
|
1499 | var args = arguments;
|
1500 | _arrayEach(tasks, function (task) {
|
1501 | task.callback.apply(task, args);
|
1502 | });
|
1503 | if (q.tasks.length + workers === 0) {
|
1504 | q.drain();
|
1505 | }
|
1506 | q.process();
|
1507 | };
|
1508 | }
|
1509 |
|
1510 | var workers = 0;
|
1511 | var q = {
|
1512 | tasks: [],
|
1513 | concurrency: concurrency,
|
1514 | payload: payload,
|
1515 | saturated: noop,
|
1516 | empty: noop,
|
1517 | drain: noop,
|
1518 | started: false,
|
1519 | paused: false,
|
1520 | push: function (data, callback) {
|
1521 | _insert(q, data, false, callback);
|
1522 | },
|
1523 | kill: function () {
|
1524 | q.drain = noop;
|
1525 | q.tasks = [];
|
1526 | },
|
1527 | unshift: function (data, callback) {
|
1528 | _insert(q, data, true, callback);
|
1529 | },
|
1530 | process: function () {
|
1531 | if (!q.paused && workers < q.concurrency && q.tasks.length) {
|
1532 | while(workers < q.concurrency && q.tasks.length){
|
1533 | var tasks = q.payload ?
|
1534 | q.tasks.splice(0, q.payload) :
|
1535 | q.tasks.splice(0, q.tasks.length);
|
1536 |
|
1537 | var data = _map(tasks, function (task) {
|
1538 | return task.data;
|
1539 | });
|
1540 |
|
1541 | if (q.tasks.length === 0) {
|
1542 | q.empty();
|
1543 | }
|
1544 | workers += 1;
|
1545 | var cb = only_once(_next(q, tasks));
|
1546 | worker(data, cb);
|
1547 | }
|
1548 | }
|
1549 | },
|
1550 | length: function () {
|
1551 | return q.tasks.length;
|
1552 | },
|
1553 | running: function () {
|
1554 | return workers;
|
1555 | },
|
1556 | idle: function() {
|
1557 | return q.tasks.length + workers === 0;
|
1558 | },
|
1559 | pause: function () {
|
1560 | q.paused = true;
|
1561 | },
|
1562 | resume: function () {
|
1563 | if (q.paused === false) { return; }
|
1564 | q.paused = false;
|
1565 | var resumeCount = Math.min(q.concurrency, q.tasks.length);
|
1566 | // Need to call q.process once per concurrent
|
1567 | // worker to preserve full concurrency after pause
|
1568 | for (var w = 1; w <= resumeCount; w++) {
|
1569 | async.setImmediate(q.process);
|
1570 | }
|
1571 | }
|
1572 | };
|
1573 | return q;
|
1574 | }
|
1575 |
|
1576 | async.queue = function (worker, concurrency) {
|
1577 | var q = _queue(function (items, cb) {
|
1578 | worker(items[0], cb);
|
1579 | }, concurrency, 1);
|
1580 |
|
1581 | return q;
|
1582 | };
|
1583 |
|
1584 | async.priorityQueue = function (worker, concurrency) {
|
1585 |
|
1586 | function _compareTasks(a, b){
|
1587 | return a.priority - b.priority;
|
1588 | }
|
1589 |
|
1590 | function _binarySearch(sequence, item, compare) {
|
1591 | var beg = -1,
|
1592 | end = sequence.length - 1;
|
1593 | while (beg < end) {
|
1594 | var mid = beg + ((end - beg + 1) >>> 1);
|
1595 | if (compare(item, sequence[mid]) >= 0) {
|
1596 | beg = mid;
|
1597 | } else {
|
1598 | end = mid - 1;
|
1599 | }
|
1600 | }
|
1601 | return beg;
|
1602 | }
|
1603 |
|
1604 | function _insert(q, data, priority, callback) {
|
1605 | if (callback != null && typeof callback !== "function") {
|
1606 | throw new Error("task callback must be a function");
|
1607 | }
|
1608 | q.started = true;
|
1609 | if (!_isArray(data)) {
|
1610 | data = [data];
|
1611 | }
|
1612 | if(data.length === 0) {
|
1613 | // call drain immediately if there are no tasks
|
1614 | return async.setImmediate(function() {
|
1615 | q.drain();
|
1616 | });
|
1617 | }
|
1618 | _arrayEach(data, function(task) {
|
1619 | var item = {
|
1620 | data: task,
|
1621 | priority: priority,
|
1622 | callback: typeof callback === 'function' ? callback : noop
|
1623 | };
|
1624 |
|
1625 | q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
|
1626 |
|
1627 | if (q.tasks.length === q.concurrency) {
|
1628 | q.saturated();
|
1629 | }
|
1630 | async.setImmediate(q.process);
|
1631 | });
|
1632 | }
|
1633 |
|
1634 | // Start with a normal queue
|
1635 | var q = async.queue(worker, concurrency);
|
1636 |
|
1637 | // Override push to accept second parameter representing priority
|
1638 | q.push = function (data, priority, callback) {
|
1639 | _insert(q, data, priority, callback);
|
1640 | };
|
1641 |
|
1642 | // Remove unshift function
|
1643 | delete q.unshift;
|
1644 |
|
1645 | return q;
|
1646 | };
|
1647 |
|
1648 | async.cargo = function (worker, payload) {
|
1649 | return _queue(worker, 1, payload);
|
1650 | };
|
1651 |
|
1652 | function _console_fn(name) {
|
1653 | return _restParam(function (fn, args) {
|
1654 | fn.apply(null, args.concat([_restParam(function (err, args) {
|
1655 | if (typeof console === 'object') {
|
1656 | if (err) {
|
1657 | if (console.error) {
|
1658 | console.error(err);
|
1659 | }
|
1660 | }
|
1661 | else if (console[name]) {
|
1662 | _arrayEach(args, function (x) {
|
1663 | console[name](x);
|
1664 | });
|
1665 | }
|
1666 | }
|
1667 | })]));
|
1668 | });
|
1669 | }
|
1670 | async.log = _console_fn('log');
|
1671 | async.dir = _console_fn('dir');
|
1672 | /*async.info = _console_fn('info');
|
1673 | async.warn = _console_fn('warn');
|
1674 | async.error = _console_fn('error');*/
|
1675 |
|
1676 | async.memoize = function (fn, hasher) {
|
1677 | var memo = {};
|
1678 | var queues = {};
|
1679 | hasher = hasher || identity;
|
1680 | var memoized = _restParam(function memoized(args) {
|
1681 | var callback = args.pop();
|
1682 | var key = hasher.apply(null, args);
|
1683 | if (key in memo) {
|
1684 | async.nextTick(function () {
|
1685 | callback.apply(null, memo[key]);
|
1686 | });
|
1687 | }
|
1688 | else if (key in queues) {
|
1689 | queues[key].push(callback);
|
1690 | }
|
1691 | else {
|
1692 | queues[key] = [callback];
|
1693 | fn.apply(null, args.concat([_restParam(function (args) {
|
1694 | memo[key] = args;
|
1695 | var q = queues[key];
|
1696 | delete queues[key];
|
1697 | for (var i = 0, l = q.length; i < l; i++) {
|
1698 | q[i].apply(null, args);
|
1699 | }
|
1700 | })]));
|
1701 | }
|
1702 | });
|
1703 | memoized.memo = memo;
|
1704 | memoized.unmemoized = fn;
|
1705 | return memoized;
|
1706 | };
|
1707 |
|
1708 | async.unmemoize = function (fn) {
|
1709 | return function () {
|
1710 | return (fn.unmemoized || fn).apply(null, arguments);
|
1711 | };
|
1712 | };
|
1713 |
|
1714 | function _times(mapper) {
|
1715 | return function (count, iterator, callback) {
|
1716 | mapper(_range(count), iterator, callback);
|
1717 | };
|
1718 | }
|
1719 |
|
1720 | async.times = _times(async.map);
|
1721 | async.timesSeries = _times(async.mapSeries);
|
1722 | async.timesLimit = function (count, limit, iterator, callback) {
|
1723 | return async.mapLimit(_range(count), limit, iterator, callback);
|
1724 | };
|
1725 |
|
1726 | async.seq = function (/* functions... */) {
|
1727 | var fns = arguments;
|
1728 | return _restParam(function (args) {
|
1729 | var that = this;
|
1730 |
|
1731 | var callback = args[args.length - 1];
|
1732 | if (typeof callback == 'function') {
|
1733 | args.pop();
|
1734 | } else {
|
1735 | callback = noop;
|
1736 | }
|
1737 |
|
1738 | async.reduce(fns, args, function (newargs, fn, cb) {
|
1739 | fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
|
1740 | cb(err, nextargs);
|
1741 | })]));
|
1742 | },
|
1743 | function (err, results) {
|
1744 | callback.apply(that, [err].concat(results));
|
1745 | });
|
1746 | });
|
1747 | };
|
1748 |
|
1749 | async.compose = function (/* functions... */) {
|
1750 | return async.seq.apply(null, Array.prototype.reverse.call(arguments));
|
1751 | };
|
1752 |
|
1753 |
|
1754 | function _applyEach(eachfn) {
|
1755 | return _restParam(function(fns, args) {
|
1756 | var go = _restParam(function(args) {
|
1757 | var that = this;
|
1758 | var callback = args.pop();
|
1759 | return eachfn(fns, function (fn, _, cb) {
|
1760 | fn.apply(that, args.concat([cb]));
|
1761 | },
|
1762 | callback);
|
1763 | });
|
1764 | if (args.length) {
|
1765 | return go.apply(this, args);
|
1766 | }
|
1767 | else {
|
1768 | return go;
|
1769 | }
|
1770 | });
|
1771 | }
|
1772 |
|
1773 | async.applyEach = _applyEach(async.eachOf);
|
1774 | async.applyEachSeries = _applyEach(async.eachOfSeries);
|
1775 |
|
1776 |
|
1777 | async.forever = function (fn, callback) {
|
1778 | var done = only_once(callback || noop);
|
1779 | var task = ensureAsync(fn);
|
1780 | function next(err) {
|
1781 | if (err) {
|
1782 | return done(err);
|
1783 | }
|
1784 | task(next);
|
1785 | }
|
1786 | next();
|
1787 | };
|
1788 |
|
1789 | function ensureAsync(fn) {
|
1790 | return _restParam(function (args) {
|
1791 | var callback = args.pop();
|
1792 | args.push(function () {
|
1793 | var innerArgs = arguments;
|
1794 | if (sync) {
|
1795 | async.setImmediate(function () {
|
1796 | callback.apply(null, innerArgs);
|
1797 | });
|
1798 | } else {
|
1799 | callback.apply(null, innerArgs);
|
1800 | }
|
1801 | });
|
1802 | var sync = true;
|
1803 | fn.apply(this, args);
|
1804 | sync = false;
|
1805 | });
|
1806 | }
|
1807 |
|
1808 | async.ensureAsync = ensureAsync;
|
1809 |
|
1810 | async.constant = _restParam(function(values) {
|
1811 | var args = [null].concat(values);
|
1812 | return function (callback) {
|
1813 | return callback.apply(this, args);
|
1814 | };
|
1815 | });
|
1816 |
|
1817 | async.wrapSync =
|
1818 | async.asyncify = function asyncify(func) {
|
1819 | return _restParam(function (args) {
|
1820 | var callback = args.pop();
|
1821 | var result;
|
1822 | try {
|
1823 | result = func.apply(this, args);
|
1824 | } catch (e) {
|
1825 | return callback(e);
|
1826 | }
|
1827 | // if result is Promise object
|
1828 | if (_isObject(result) && typeof result.then === "function") {
|
1829 | result.then(function(value) {
|
1830 | callback(null, value);
|
1831 | })["catch"](function(err) {
|
1832 | callback(err.message ? err : new Error(err));
|
1833 | });
|
1834 | } else {
|
1835 | callback(null, result);
|
1836 | }
|
1837 | });
|
1838 | };
|
1839 |
|
1840 | // Node.js
|
1841 | if (typeof module === 'object' && module.exports) {
|
1842 | module.exports = async;
|
1843 | }
|
1844 | // AMD / RequireJS
|
1845 | else if (typeof define === 'function' && define.amd) {
|
1846 | define([], function () {
|
1847 | return async;
|
1848 | });
|
1849 | }
|
1850 | // included directly via <script> tag
|
1851 | else {
|
1852 | root.async = async;
|
1853 | }
|
1854 |
|
1855 | }());
|
1856 |
|
1857 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
|
1858 | },{"_process":9}],3:[function(require,module,exports){
|
1859 | (function (Buffer){
|
1860 | var FNV = require('fnv').FNV
|
1861 |
|
1862 | var Blomma = function (size, rounds) {
|
1863 | var indicies = function (value) {
|
1864 | var hash = new FNV()
|
1865 | var idx = []
|
1866 |
|
1867 | for (var i = 0 ; i < rounds ; i++) {
|
1868 | hash.update(value)
|
1869 | idx.push(parseInt(hash.digest('hex'), 16) % (size * 8))
|
1870 | value = '\0'
|
1871 | }
|
1872 | return idx
|
1873 | }
|
1874 |
|
1875 | var Filter = function (databuf) {
|
1876 | this.buffer = new Buffer(databuf || size)
|
1877 | if (!databuf) this.buffer.fill(0)
|
1878 | }
|
1879 |
|
1880 | Filter.prototype = {
|
1881 | add: function (value) {
|
1882 | var idx = indicies(value)
|
1883 | for (var i = 0 ; i < rounds ; i++) {
|
1884 | var bit = idx[i]
|
1885 | this.buffer[bit >> 3] |= (1 << (bit % 8))
|
1886 | }
|
1887 | },
|
1888 | has: function (value) {
|
1889 | var idx = indicies(value)
|
1890 | for (var i = 0 ; i < rounds ; i++) {
|
1891 | var bit = idx[i]
|
1892 | if (!(this.buffer[bit >> 3] & (1 << (bit % 8)))) {
|
1893 | return false
|
1894 | }
|
1895 | }
|
1896 | return true
|
1897 | },
|
1898 | contains: function (subset) {
|
1899 | for (var i = 0 ; i < size ; i++) {
|
1900 | if ((this.buffer[i] & subset.buffer[i]) !== subset.buffer[i]) {
|
1901 | return false
|
1902 | }
|
1903 | }
|
1904 | return true
|
1905 | }
|
1906 | }
|
1907 |
|
1908 | return {
|
1909 | empty: function () {
|
1910 | return new Filter()
|
1911 | },
|
1912 | fromBuffer: function (buf) {
|
1913 | return new Filter(buf)
|
1914 | },
|
1915 | merge: function (a, b) {
|
1916 | var filter = new Filter()
|
1917 | for (var i = 0 ; i < size ; i++) {
|
1918 | filter.buffer[i] = a.buffer[i] | b.buffer[i]
|
1919 | }
|
1920 | return filter
|
1921 | },
|
1922 | clone: function (toclone) {
|
1923 | var filter = new Filter()
|
1924 | for (var i = 0 ; i < size ; i++) {
|
1925 | filter.buffer[i] = toclone.buffer[i]
|
1926 | }
|
1927 | return filter
|
1928 | }
|
1929 | }
|
1930 | }
|
1931 |
|
1932 | module.exports = Blomma
|
1933 |
|
1934 | }).call(this,require("buffer").Buffer)
|
1935 | },{"buffer":5,"fnv":4}],4:[function(require,module,exports){
|
1936 | (function (Buffer){
|
1937 | "use strict"
|
1938 | /* implement http://tools.ietf.org/html/draft-eastlake-fnv-04 */
|
1939 |
|
1940 | function FNV() {
|
1941 | this.hash = 0x811C9DC5 /* offset_basis */
|
1942 | }
|
1943 |
|
1944 | FNV.prototype = {
|
1945 | update: function(data) {
|
1946 | if(typeof data === 'string') {
|
1947 | data = Buffer(data)
|
1948 | } else if(!(data instanceof Buffer)) {
|
1949 | throw Error("FNV.update expectes String or Buffer")
|
1950 | }
|
1951 | for(var i = 0; i < data.length; i++) {
|
1952 | this.hash = this.hash ^ data[i]
|
1953 | /* 32 bit FNV_Prime = 2**24 + 2**8 + 0x93 */
|
1954 | this.hash += (this.hash << 24) + (this.hash << 8) + (this.hash << 7) + (this.hash << 4) + (this.hash << 1)
|
1955 | }
|
1956 |
|
1957 | // Make API chainable
|
1958 | return this;
|
1959 | },
|
1960 | digest: function(encoding) {
|
1961 | encoding = encoding || "binary"
|
1962 | var buf = new Buffer(4)
|
1963 | buf.writeInt32BE(this.hash & 0xffffffff, 0)
|
1964 | return buf.toString(encoding)
|
1965 | },
|
1966 | value: function() {
|
1967 | return this.hash & 0xffffffff
|
1968 | }
|
1969 | }
|
1970 |
|
1971 | exports.FNV = FNV
|
1972 | }).call(this,require("buffer").Buffer)
|
1973 | },{"buffer":5}],5:[function(require,module,exports){
|
1974 | /*!
|
1975 | * The buffer module from node.js, for the browser.
|
1976 | *
|
1977 | * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
|
1978 | * @license MIT
|
1979 | */
|
1980 |
|
1981 | var base64 = require('base64-js')
|
1982 | var ieee754 = require('ieee754')
|
1983 | var isArray = require('is-array')
|
1984 |
|
1985 | exports.Buffer = Buffer
|
1986 | exports.SlowBuffer = SlowBuffer
|
1987 | exports.INSPECT_MAX_BYTES = 50
|
1988 | Buffer.poolSize = 8192 // not used by this implementation
|
1989 |
|
1990 | var rootParent = {}
|
1991 |
|
1992 | /**
|
1993 | * If `Buffer.TYPED_ARRAY_SUPPORT`:
|
1994 | * === true Use Uint8Array implementation (fastest)
|
1995 | * === false Use Object implementation (most compatible, even IE6)
|
1996 | *
|
1997 | * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
|
1998 | * Opera 11.6+, iOS 4.2+.
|
1999 | *
|
2000 | * Due to various browser bugs, sometimes the Object implementation will be used even
|
2001 | * when the browser supports typed arrays.
|
2002 | *
|
2003 | * Note:
|
2004 | *
|
2005 | * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
|
2006 | * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
|
2007 | *
|
2008 | * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
|
2009 | * on objects.
|
2010 | *
|
2011 | * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
|
2012 | *
|
2013 | * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
|
2014 | * incorrect length in some situations.
|
2015 |
|
2016 | * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
|
2017 | * get the Object implementation, which is slower but behaves correctly.
|
2018 | */
|
2019 | Buffer.TYPED_ARRAY_SUPPORT = (function () {
|
2020 | function Bar () {}
|
2021 | try {
|
2022 | var arr = new Uint8Array(1)
|
2023 | arr.foo = function () { return 42 }
|
2024 | arr.constructor = Bar
|
2025 | return arr.foo() === 42 && // typed array instances can be augmented
|
2026 | arr.constructor === Bar && // constructor can be set
|
2027 | typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
|
2028 | arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
|
2029 | } catch (e) {
|
2030 | return false
|
2031 | }
|
2032 | })()
|
2033 |
|
2034 | function kMaxLength () {
|
2035 | return Buffer.TYPED_ARRAY_SUPPORT
|
2036 | ? 0x7fffffff
|
2037 | : 0x3fffffff
|
2038 | }
|
2039 |
|
2040 | /**
|
2041 | * Class: Buffer
|
2042 | * =============
|
2043 | *
|
2044 | * The Buffer constructor returns instances of `Uint8Array` that are augmented
|
2045 | * with function properties for all the node `Buffer` API functions. We use
|
2046 | * `Uint8Array` so that square bracket notation works as expected -- it returns
|
2047 | * a single octet.
|
2048 | *
|
2049 | * By augmenting the instances, we can avoid modifying the `Uint8Array`
|
2050 | * prototype.
|
2051 | */
|
2052 | function Buffer (arg) {
|
2053 | if (!(this instanceof Buffer)) {
|
2054 | // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
|
2055 | if (arguments.length > 1) return new Buffer(arg, arguments[1])
|
2056 | return new Buffer(arg)
|
2057 | }
|
2058 |
|
2059 | this.length = 0
|
2060 | this.parent = undefined
|
2061 |
|
2062 | // Common case.
|
2063 | if (typeof arg === 'number') {
|
2064 | return fromNumber(this, arg)
|
2065 | }
|
2066 |
|
2067 | // Slightly less common case.
|
2068 | if (typeof arg === 'string') {
|
2069 | return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
|
2070 | }
|
2071 |
|
2072 | // Unusual.
|
2073 | return fromObject(this, arg)
|
2074 | }
|
2075 |
|
2076 | function fromNumber (that, length) {
|
2077 | that = allocate(that, length < 0 ? 0 : checked(length) | 0)
|
2078 | if (!Buffer.TYPED_ARRAY_SUPPORT) {
|
2079 | for (var i = 0; i < length; i++) {
|
2080 | that[i] = 0
|
2081 | }
|
2082 | }
|
2083 | return that
|
2084 | }
|
2085 |
|
2086 | function fromString (that, string, encoding) {
|
2087 | if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
|
2088 |
|
2089 | // Assumption: byteLength() return value is always < kMaxLength.
|
2090 | var length = byteLength(string, encoding) | 0
|
2091 | that = allocate(that, length)
|
2092 |
|
2093 | that.write(string, encoding)
|
2094 | return that
|
2095 | }
|
2096 |
|
2097 | function fromObject (that, object) {
|
2098 | if (Buffer.isBuffer(object)) return fromBuffer(that, object)
|
2099 |
|
2100 | if (isArray(object)) return fromArray(that, object)
|
2101 |
|
2102 | if (object == null) {
|
2103 | throw new TypeError('must start with number, buffer, array or string')
|
2104 | }
|
2105 |
|
2106 | if (typeof ArrayBuffer !== 'undefined') {
|
2107 | if (object.buffer instanceof ArrayBuffer) {
|
2108 | return fromTypedArray(that, object)
|
2109 | }
|
2110 | if (object instanceof ArrayBuffer) {
|
2111 | return fromArrayBuffer(that, object)
|
2112 | }
|
2113 | }
|
2114 |
|
2115 | if (object.length) return fromArrayLike(that, object)
|
2116 |
|
2117 | return fromJsonObject(that, object)
|
2118 | }
|
2119 |
|
2120 | function fromBuffer (that, buffer) {
|
2121 | var length = checked(buffer.length) | 0
|
2122 | that = allocate(that, length)
|
2123 | buffer.copy(that, 0, 0, length)
|
2124 | return that
|
2125 | }
|
2126 |
|
2127 | function fromArray (that, array) {
|
2128 | var length = checked(array.length) | 0
|
2129 | that = allocate(that, length)
|
2130 | for (var i = 0; i < length; i += 1) {
|
2131 | that[i] = array[i] & 255
|
2132 | }
|
2133 | return that
|
2134 | }
|
2135 |
|
2136 | // Duplicate of fromArray() to keep fromArray() monomorphic.
|
2137 | function fromTypedArray (that, array) {
|
2138 | var length = checked(array.length) | 0
|
2139 | that = allocate(that, length)
|
2140 | // Truncating the elements is probably not what people expect from typed
|
2141 | // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
|
2142 | // of the old Buffer constructor.
|
2143 | for (var i = 0; i < length; i += 1) {
|
2144 | that[i] = array[i] & 255
|
2145 | }
|
2146 | return that
|
2147 | }
|
2148 |
|
2149 | function fromArrayBuffer (that, array) {
|
2150 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
2151 | // Return an augmented `Uint8Array` instance, for best performance
|
2152 | array.byteLength
|
2153 | that = Buffer._augment(new Uint8Array(array))
|
2154 | } else {
|
2155 | // Fallback: Return an object instance of the Buffer class
|
2156 | that = fromTypedArray(that, new Uint8Array(array))
|
2157 | }
|
2158 | return that
|
2159 | }
|
2160 |
|
2161 | function fromArrayLike (that, array) {
|
2162 | var length = checked(array.length) | 0
|
2163 | that = allocate(that, length)
|
2164 | for (var i = 0; i < length; i += 1) {
|
2165 | that[i] = array[i] & 255
|
2166 | }
|
2167 | return that
|
2168 | }
|
2169 |
|
2170 | // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
|
2171 | // Returns a zero-length buffer for inputs that don't conform to the spec.
|
2172 | function fromJsonObject (that, object) {
|
2173 | var array
|
2174 | var length = 0
|
2175 |
|
2176 | if (object.type === 'Buffer' && isArray(object.data)) {
|
2177 | array = object.data
|
2178 | length = checked(array.length) | 0
|
2179 | }
|
2180 | that = allocate(that, length)
|
2181 |
|
2182 | for (var i = 0; i < length; i += 1) {
|
2183 | that[i] = array[i] & 255
|
2184 | }
|
2185 | return that
|
2186 | }
|
2187 |
|
2188 | function allocate (that, length) {
|
2189 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
2190 | // Return an augmented `Uint8Array` instance, for best performance
|
2191 | that = Buffer._augment(new Uint8Array(length))
|
2192 | } else {
|
2193 | // Fallback: Return an object instance of the Buffer class
|
2194 | that.length = length
|
2195 | that._isBuffer = true
|
2196 | }
|
2197 |
|
2198 | var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
|
2199 | if (fromPool) that.parent = rootParent
|
2200 |
|
2201 | return that
|
2202 | }
|
2203 |
|
2204 | function checked (length) {
|
2205 | // Note: cannot use `length < kMaxLength` here because that fails when
|
2206 | // length is NaN (which is otherwise coerced to zero.)
|
2207 | if (length >= kMaxLength()) {
|
2208 | throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
|
2209 | 'size: 0x' + kMaxLength().toString(16) + ' bytes')
|
2210 | }
|
2211 | return length | 0
|
2212 | }
|
2213 |
|
2214 | function SlowBuffer (subject, encoding) {
|
2215 | if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
|
2216 |
|
2217 | var buf = new Buffer(subject, encoding)
|
2218 | delete buf.parent
|
2219 | return buf
|
2220 | }
|
2221 |
|
2222 | Buffer.isBuffer = function isBuffer (b) {
|
2223 | return !!(b != null && b._isBuffer)
|
2224 | }
|
2225 |
|
2226 | Buffer.compare = function compare (a, b) {
|
2227 | if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
|
2228 | throw new TypeError('Arguments must be Buffers')
|
2229 | }
|
2230 |
|
2231 | if (a === b) return 0
|
2232 |
|
2233 | var x = a.length
|
2234 | var y = b.length
|
2235 |
|
2236 | var i = 0
|
2237 | var len = Math.min(x, y)
|
2238 | while (i < len) {
|
2239 | if (a[i] !== b[i]) break
|
2240 |
|
2241 | ++i
|
2242 | }
|
2243 |
|
2244 | if (i !== len) {
|
2245 | x = a[i]
|
2246 | y = b[i]
|
2247 | }
|
2248 |
|
2249 | if (x < y) return -1
|
2250 | if (y < x) return 1
|
2251 | return 0
|
2252 | }
|
2253 |
|
2254 | Buffer.isEncoding = function isEncoding (encoding) {
|
2255 | switch (String(encoding).toLowerCase()) {
|
2256 | case 'hex':
|
2257 | case 'utf8':
|
2258 | case 'utf-8':
|
2259 | case 'ascii':
|
2260 | case 'binary':
|
2261 | case 'base64':
|
2262 | case 'raw':
|
2263 | case 'ucs2':
|
2264 | case 'ucs-2':
|
2265 | case 'utf16le':
|
2266 | case 'utf-16le':
|
2267 | return true
|
2268 | default:
|
2269 | return false
|
2270 | }
|
2271 | }
|
2272 |
|
2273 | Buffer.concat = function concat (list, length) {
|
2274 | if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
|
2275 |
|
2276 | if (list.length === 0) {
|
2277 | return new Buffer(0)
|
2278 | }
|
2279 |
|
2280 | var i
|
2281 | if (length === undefined) {
|
2282 | length = 0
|
2283 | for (i = 0; i < list.length; i++) {
|
2284 | length += list[i].length
|
2285 | }
|
2286 | }
|
2287 |
|
2288 | var buf = new Buffer(length)
|
2289 | var pos = 0
|
2290 | for (i = 0; i < list.length; i++) {
|
2291 | var item = list[i]
|
2292 | item.copy(buf, pos)
|
2293 | pos += item.length
|
2294 | }
|
2295 | return buf
|
2296 | }
|
2297 |
|
2298 | function byteLength (string, encoding) {
|
2299 | if (typeof string !== 'string') string = '' + string
|
2300 |
|
2301 | var len = string.length
|
2302 | if (len === 0) return 0
|
2303 |
|
2304 | // Use a for loop to avoid recursion
|
2305 | var loweredCase = false
|
2306 | for (;;) {
|
2307 | switch (encoding) {
|
2308 | case 'ascii':
|
2309 | case 'binary':
|
2310 | // Deprecated
|
2311 | case 'raw':
|
2312 | case 'raws':
|
2313 | return len
|
2314 | case 'utf8':
|
2315 | case 'utf-8':
|
2316 | return utf8ToBytes(string).length
|
2317 | case 'ucs2':
|
2318 | case 'ucs-2':
|
2319 | case 'utf16le':
|
2320 | case 'utf-16le':
|
2321 | return len * 2
|
2322 | case 'hex':
|
2323 | return len >>> 1
|
2324 | case 'base64':
|
2325 | return base64ToBytes(string).length
|
2326 | default:
|
2327 | if (loweredCase) return utf8ToBytes(string).length // assume utf8
|
2328 | encoding = ('' + encoding).toLowerCase()
|
2329 | loweredCase = true
|
2330 | }
|
2331 | }
|
2332 | }
|
2333 | Buffer.byteLength = byteLength
|
2334 |
|
2335 | // pre-set for values that may exist in the future
|
2336 | Buffer.prototype.length = undefined
|
2337 | Buffer.prototype.parent = undefined
|
2338 |
|
2339 | function slowToString (encoding, start, end) {
|
2340 | var loweredCase = false
|
2341 |
|
2342 | start = start | 0
|
2343 | end = end === undefined || end === Infinity ? this.length : end | 0
|
2344 |
|
2345 | if (!encoding) encoding = 'utf8'
|
2346 | if (start < 0) start = 0
|
2347 | if (end > this.length) end = this.length
|
2348 | if (end <= start) return ''
|
2349 |
|
2350 | while (true) {
|
2351 | switch (encoding) {
|
2352 | case 'hex':
|
2353 | return hexSlice(this, start, end)
|
2354 |
|
2355 | case 'utf8':
|
2356 | case 'utf-8':
|
2357 | return utf8Slice(this, start, end)
|
2358 |
|
2359 | case 'ascii':
|
2360 | return asciiSlice(this, start, end)
|
2361 |
|
2362 | case 'binary':
|
2363 | return binarySlice(this, start, end)
|
2364 |
|
2365 | case 'base64':
|
2366 | return base64Slice(this, start, end)
|
2367 |
|
2368 | case 'ucs2':
|
2369 | case 'ucs-2':
|
2370 | case 'utf16le':
|
2371 | case 'utf-16le':
|
2372 | return utf16leSlice(this, start, end)
|
2373 |
|
2374 | default:
|
2375 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
|
2376 | encoding = (encoding + '').toLowerCase()
|
2377 | loweredCase = true
|
2378 | }
|
2379 | }
|
2380 | }
|
2381 |
|
2382 | Buffer.prototype.toString = function toString () {
|
2383 | var length = this.length | 0
|
2384 | if (length === 0) return ''
|
2385 | if (arguments.length === 0) return utf8Slice(this, 0, length)
|
2386 | return slowToString.apply(this, arguments)
|
2387 | }
|
2388 |
|
2389 | Buffer.prototype.equals = function equals (b) {
|
2390 | if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
|
2391 | if (this === b) return true
|
2392 | return Buffer.compare(this, b) === 0
|
2393 | }
|
2394 |
|
2395 | Buffer.prototype.inspect = function inspect () {
|
2396 | var str = ''
|
2397 | var max = exports.INSPECT_MAX_BYTES
|
2398 | if (this.length > 0) {
|
2399 | str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
|
2400 | if (this.length > max) str += ' ... '
|
2401 | }
|
2402 | return '<Buffer ' + str + '>'
|
2403 | }
|
2404 |
|
2405 | Buffer.prototype.compare = function compare (b) {
|
2406 | if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
|
2407 | if (this === b) return 0
|
2408 | return Buffer.compare(this, b)
|
2409 | }
|
2410 |
|
2411 | Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
|
2412 | if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
|
2413 | else if (byteOffset < -0x80000000) byteOffset = -0x80000000
|
2414 | byteOffset >>= 0
|
2415 |
|
2416 | if (this.length === 0) return -1
|
2417 | if (byteOffset >= this.length) return -1
|
2418 |
|
2419 | // Negative offsets start from the end of the buffer
|
2420 | if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
|
2421 |
|
2422 | if (typeof val === 'string') {
|
2423 | if (val.length === 0) return -1 // special case: looking for empty string always fails
|
2424 | return String.prototype.indexOf.call(this, val, byteOffset)
|
2425 | }
|
2426 | if (Buffer.isBuffer(val)) {
|
2427 | return arrayIndexOf(this, val, byteOffset)
|
2428 | }
|
2429 | if (typeof val === 'number') {
|
2430 | if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
|
2431 | return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
|
2432 | }
|
2433 | return arrayIndexOf(this, [ val ], byteOffset)
|
2434 | }
|
2435 |
|
2436 | function arrayIndexOf (arr, val, byteOffset) {
|
2437 | var foundIndex = -1
|
2438 | for (var i = 0; byteOffset + i < arr.length; i++) {
|
2439 | if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
|
2440 | if (foundIndex === -1) foundIndex = i
|
2441 | if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
|
2442 | } else {
|
2443 | foundIndex = -1
|
2444 | }
|
2445 | }
|
2446 | return -1
|
2447 | }
|
2448 |
|
2449 | throw new TypeError('val must be string, number or Buffer')
|
2450 | }
|
2451 |
|
2452 | // `get` is deprecated
|
2453 | Buffer.prototype.get = function get (offset) {
|
2454 | console.log('.get() is deprecated. Access using array indexes instead.')
|
2455 | return this.readUInt8(offset)
|
2456 | }
|
2457 |
|
2458 | // `set` is deprecated
|
2459 | Buffer.prototype.set = function set (v, offset) {
|
2460 | console.log('.set() is deprecated. Access using array indexes instead.')
|
2461 | return this.writeUInt8(v, offset)
|
2462 | }
|
2463 |
|
2464 | function hexWrite (buf, string, offset, length) {
|
2465 | offset = Number(offset) || 0
|
2466 | var remaining = buf.length - offset
|
2467 | if (!length) {
|
2468 | length = remaining
|
2469 | } else {
|
2470 | length = Number(length)
|
2471 | if (length > remaining) {
|
2472 | length = remaining
|
2473 | }
|
2474 | }
|
2475 |
|
2476 | // must be an even number of digits
|
2477 | var strLen = string.length
|
2478 | if (strLen % 2 !== 0) throw new Error('Invalid hex string')
|
2479 |
|
2480 | if (length > strLen / 2) {
|
2481 | length = strLen / 2
|
2482 | }
|
2483 | for (var i = 0; i < length; i++) {
|
2484 | var parsed = parseInt(string.substr(i * 2, 2), 16)
|
2485 | if (isNaN(parsed)) throw new Error('Invalid hex string')
|
2486 | buf[offset + i] = parsed
|
2487 | }
|
2488 | return i
|
2489 | }
|
2490 |
|
2491 | function utf8Write (buf, string, offset, length) {
|
2492 | return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
|
2493 | }
|
2494 |
|
2495 | function asciiWrite (buf, string, offset, length) {
|
2496 | return blitBuffer(asciiToBytes(string), buf, offset, length)
|
2497 | }
|
2498 |
|
2499 | function binaryWrite (buf, string, offset, length) {
|
2500 | return asciiWrite(buf, string, offset, length)
|
2501 | }
|
2502 |
|
2503 | function base64Write (buf, string, offset, length) {
|
2504 | return blitBuffer(base64ToBytes(string), buf, offset, length)
|
2505 | }
|
2506 |
|
2507 | function ucs2Write (buf, string, offset, length) {
|
2508 | return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
|
2509 | }
|
2510 |
|
2511 | Buffer.prototype.write = function write (string, offset, length, encoding) {
|
2512 | // Buffer#write(string)
|
2513 | if (offset === undefined) {
|
2514 | encoding = 'utf8'
|
2515 | length = this.length
|
2516 | offset = 0
|
2517 | // Buffer#write(string, encoding)
|
2518 | } else if (length === undefined && typeof offset === 'string') {
|
2519 | encoding = offset
|
2520 | length = this.length
|
2521 | offset = 0
|
2522 | // Buffer#write(string, offset[, length][, encoding])
|
2523 | } else if (isFinite(offset)) {
|
2524 | offset = offset | 0
|
2525 | if (isFinite(length)) {
|
2526 | length = length | 0
|
2527 | if (encoding === undefined) encoding = 'utf8'
|
2528 | } else {
|
2529 | encoding = length
|
2530 | length = undefined
|
2531 | }
|
2532 | // legacy write(string, encoding, offset, length) - remove in v0.13
|
2533 | } else {
|
2534 | var swap = encoding
|
2535 | encoding = offset
|
2536 | offset = length | 0
|
2537 | length = swap
|
2538 | }
|
2539 |
|
2540 | var remaining = this.length - offset
|
2541 | if (length === undefined || length > remaining) length = remaining
|
2542 |
|
2543 | if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
|
2544 | throw new RangeError('attempt to write outside buffer bounds')
|
2545 | }
|
2546 |
|
2547 | if (!encoding) encoding = 'utf8'
|
2548 |
|
2549 | var loweredCase = false
|
2550 | for (;;) {
|
2551 | switch (encoding) {
|
2552 | case 'hex':
|
2553 | return hexWrite(this, string, offset, length)
|
2554 |
|
2555 | case 'utf8':
|
2556 | case 'utf-8':
|
2557 | return utf8Write(this, string, offset, length)
|
2558 |
|
2559 | case 'ascii':
|
2560 | return asciiWrite(this, string, offset, length)
|
2561 |
|
2562 | case 'binary':
|
2563 | return binaryWrite(this, string, offset, length)
|
2564 |
|
2565 | case 'base64':
|
2566 | // Warning: maxLength not taken into account in base64Write
|
2567 | return base64Write(this, string, offset, length)
|
2568 |
|
2569 | case 'ucs2':
|
2570 | case 'ucs-2':
|
2571 | case 'utf16le':
|
2572 | case 'utf-16le':
|
2573 | return ucs2Write(this, string, offset, length)
|
2574 |
|
2575 | default:
|
2576 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
|
2577 | encoding = ('' + encoding).toLowerCase()
|
2578 | loweredCase = true
|
2579 | }
|
2580 | }
|
2581 | }
|
2582 |
|
2583 | Buffer.prototype.toJSON = function toJSON () {
|
2584 | return {
|
2585 | type: 'Buffer',
|
2586 | data: Array.prototype.slice.call(this._arr || this, 0)
|
2587 | }
|
2588 | }
|
2589 |
|
2590 | function base64Slice (buf, start, end) {
|
2591 | if (start === 0 && end === buf.length) {
|
2592 | return base64.fromByteArray(buf)
|
2593 | } else {
|
2594 | return base64.fromByteArray(buf.slice(start, end))
|
2595 | }
|
2596 | }
|
2597 |
|
2598 | function utf8Slice (buf, start, end) {
|
2599 | end = Math.min(buf.length, end)
|
2600 | var res = []
|
2601 |
|
2602 | var i = start
|
2603 | while (i < end) {
|
2604 | var firstByte = buf[i]
|
2605 | var codePoint = null
|
2606 | var bytesPerSequence = (firstByte > 0xEF) ? 4
|
2607 | : (firstByte > 0xDF) ? 3
|
2608 | : (firstByte > 0xBF) ? 2
|
2609 | : 1
|
2610 |
|
2611 | if (i + bytesPerSequence <= end) {
|
2612 | var secondByte, thirdByte, fourthByte, tempCodePoint
|
2613 |
|
2614 | switch (bytesPerSequence) {
|
2615 | case 1:
|
2616 | if (firstByte < 0x80) {
|
2617 | codePoint = firstByte
|
2618 | }
|
2619 | break
|
2620 | case 2:
|
2621 | secondByte = buf[i + 1]
|
2622 | if ((secondByte & 0xC0) === 0x80) {
|
2623 | tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
|
2624 | if (tempCodePoint > 0x7F) {
|
2625 | codePoint = tempCodePoint
|
2626 | }
|
2627 | }
|
2628 | break
|
2629 | case 3:
|
2630 | secondByte = buf[i + 1]
|
2631 | thirdByte = buf[i + 2]
|
2632 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
|
2633 | tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
|
2634 | if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
|
2635 | codePoint = tempCodePoint
|
2636 | }
|
2637 | }
|
2638 | break
|
2639 | case 4:
|
2640 | secondByte = buf[i + 1]
|
2641 | thirdByte = buf[i + 2]
|
2642 | fourthByte = buf[i + 3]
|
2643 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
|
2644 | tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
|
2645 | if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
|
2646 | codePoint = tempCodePoint
|
2647 | }
|
2648 | }
|
2649 | }
|
2650 | }
|
2651 |
|
2652 | if (codePoint === null) {
|
2653 | // we did not generate a valid codePoint so insert a
|
2654 | // replacement char (U+FFFD) and advance only 1 byte
|
2655 | codePoint = 0xFFFD
|
2656 | bytesPerSequence = 1
|
2657 | } else if (codePoint > 0xFFFF) {
|
2658 | // encode to utf16 (surrogate pair dance)
|
2659 | codePoint -= 0x10000
|
2660 | res.push(codePoint >>> 10 & 0x3FF | 0xD800)
|
2661 | codePoint = 0xDC00 | codePoint & 0x3FF
|
2662 | }
|
2663 |
|
2664 | res.push(codePoint)
|
2665 | i += bytesPerSequence
|
2666 | }
|
2667 |
|
2668 | return decodeCodePointsArray(res)
|
2669 | }
|
2670 |
|
2671 | // Based on http://stackoverflow.com/a/22747272/680742, the browser with
|
2672 | // the lowest limit is Chrome, with 0x10000 args.
|
2673 | // We go 1 magnitude less, for safety
|
2674 | var MAX_ARGUMENTS_LENGTH = 0x1000
|
2675 |
|
2676 | function decodeCodePointsArray (codePoints) {
|
2677 | var len = codePoints.length
|
2678 | if (len <= MAX_ARGUMENTS_LENGTH) {
|
2679 | return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
|
2680 | }
|
2681 |
|
2682 | // Decode in chunks to avoid "call stack size exceeded".
|
2683 | var res = ''
|
2684 | var i = 0
|
2685 | while (i < len) {
|
2686 | res += String.fromCharCode.apply(
|
2687 | String,
|
2688 | codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
|
2689 | )
|
2690 | }
|
2691 | return res
|
2692 | }
|
2693 |
|
2694 | function asciiSlice (buf, start, end) {
|
2695 | var ret = ''
|
2696 | end = Math.min(buf.length, end)
|
2697 |
|
2698 | for (var i = start; i < end; i++) {
|
2699 | ret += String.fromCharCode(buf[i] & 0x7F)
|
2700 | }
|
2701 | return ret
|
2702 | }
|
2703 |
|
2704 | function binarySlice (buf, start, end) {
|
2705 | var ret = ''
|
2706 | end = Math.min(buf.length, end)
|
2707 |
|
2708 | for (var i = start; i < end; i++) {
|
2709 | ret += String.fromCharCode(buf[i])
|
2710 | }
|
2711 | return ret
|
2712 | }
|
2713 |
|
2714 | function hexSlice (buf, start, end) {
|
2715 | var len = buf.length
|
2716 |
|
2717 | if (!start || start < 0) start = 0
|
2718 | if (!end || end < 0 || end > len) end = len
|
2719 |
|
2720 | var out = ''
|
2721 | for (var i = start; i < end; i++) {
|
2722 | out += toHex(buf[i])
|
2723 | }
|
2724 | return out
|
2725 | }
|
2726 |
|
2727 | function utf16leSlice (buf, start, end) {
|
2728 | var bytes = buf.slice(start, end)
|
2729 | var res = ''
|
2730 | for (var i = 0; i < bytes.length; i += 2) {
|
2731 | res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
|
2732 | }
|
2733 | return res
|
2734 | }
|
2735 |
|
2736 | Buffer.prototype.slice = function slice (start, end) {
|
2737 | var len = this.length
|
2738 | start = ~~start
|
2739 | end = end === undefined ? len : ~~end
|
2740 |
|
2741 | if (start < 0) {
|
2742 | start += len
|
2743 | if (start < 0) start = 0
|
2744 | } else if (start > len) {
|
2745 | start = len
|
2746 | }
|
2747 |
|
2748 | if (end < 0) {
|
2749 | end += len
|
2750 | if (end < 0) end = 0
|
2751 | } else if (end > len) {
|
2752 | end = len
|
2753 | }
|
2754 |
|
2755 | if (end < start) end = start
|
2756 |
|
2757 | var newBuf
|
2758 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
2759 | newBuf = Buffer._augment(this.subarray(start, end))
|
2760 | } else {
|
2761 | var sliceLen = end - start
|
2762 | newBuf = new Buffer(sliceLen, undefined)
|
2763 | for (var i = 0; i < sliceLen; i++) {
|
2764 | newBuf[i] = this[i + start]
|
2765 | }
|
2766 | }
|
2767 |
|
2768 | if (newBuf.length) newBuf.parent = this.parent || this
|
2769 |
|
2770 | return newBuf
|
2771 | }
|
2772 |
|
2773 | /*
|
2774 | * Need to make sure that buffer isn't trying to write out of bounds.
|
2775 | */
|
2776 | function checkOffset (offset, ext, length) {
|
2777 | if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
|
2778 | if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
|
2779 | }
|
2780 |
|
2781 | Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
|
2782 | offset = offset | 0
|
2783 | byteLength = byteLength | 0
|
2784 | if (!noAssert) checkOffset(offset, byteLength, this.length)
|
2785 |
|
2786 | var val = this[offset]
|
2787 | var mul = 1
|
2788 | var i = 0
|
2789 | while (++i < byteLength && (mul *= 0x100)) {
|
2790 | val += this[offset + i] * mul
|
2791 | }
|
2792 |
|
2793 | return val
|
2794 | }
|
2795 |
|
2796 | Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
|
2797 | offset = offset | 0
|
2798 | byteLength = byteLength | 0
|
2799 | if (!noAssert) {
|
2800 | checkOffset(offset, byteLength, this.length)
|
2801 | }
|
2802 |
|
2803 | var val = this[offset + --byteLength]
|
2804 | var mul = 1
|
2805 | while (byteLength > 0 && (mul *= 0x100)) {
|
2806 | val += this[offset + --byteLength] * mul
|
2807 | }
|
2808 |
|
2809 | return val
|
2810 | }
|
2811 |
|
2812 | Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
|
2813 | if (!noAssert) checkOffset(offset, 1, this.length)
|
2814 | return this[offset]
|
2815 | }
|
2816 |
|
2817 | Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
|
2818 | if (!noAssert) checkOffset(offset, 2, this.length)
|
2819 | return this[offset] | (this[offset + 1] << 8)
|
2820 | }
|
2821 |
|
2822 | Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
|
2823 | if (!noAssert) checkOffset(offset, 2, this.length)
|
2824 | return (this[offset] << 8) | this[offset + 1]
|
2825 | }
|
2826 |
|
2827 | Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
|
2828 | if (!noAssert) checkOffset(offset, 4, this.length)
|
2829 |
|
2830 | return ((this[offset]) |
|
2831 | (this[offset + 1] << 8) |
|
2832 | (this[offset + 2] << 16)) +
|
2833 | (this[offset + 3] * 0x1000000)
|
2834 | }
|
2835 |
|
2836 | Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
|
2837 | if (!noAssert) checkOffset(offset, 4, this.length)
|
2838 |
|
2839 | return (this[offset] * 0x1000000) +
|
2840 | ((this[offset + 1] << 16) |
|
2841 | (this[offset + 2] << 8) |
|
2842 | this[offset + 3])
|
2843 | }
|
2844 |
|
2845 | Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
|
2846 | offset = offset | 0
|
2847 | byteLength = byteLength | 0
|
2848 | if (!noAssert) checkOffset(offset, byteLength, this.length)
|
2849 |
|
2850 | var val = this[offset]
|
2851 | var mul = 1
|
2852 | var i = 0
|
2853 | while (++i < byteLength && (mul *= 0x100)) {
|
2854 | val += this[offset + i] * mul
|
2855 | }
|
2856 | mul *= 0x80
|
2857 |
|
2858 | if (val >= mul) val -= Math.pow(2, 8 * byteLength)
|
2859 |
|
2860 | return val
|
2861 | }
|
2862 |
|
2863 | Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
|
2864 | offset = offset | 0
|
2865 | byteLength = byteLength | 0
|
2866 | if (!noAssert) checkOffset(offset, byteLength, this.length)
|
2867 |
|
2868 | var i = byteLength
|
2869 | var mul = 1
|
2870 | var val = this[offset + --i]
|
2871 | while (i > 0 && (mul *= 0x100)) {
|
2872 | val += this[offset + --i] * mul
|
2873 | }
|
2874 | mul *= 0x80
|
2875 |
|
2876 | if (val >= mul) val -= Math.pow(2, 8 * byteLength)
|
2877 |
|
2878 | return val
|
2879 | }
|
2880 |
|
2881 | Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
|
2882 | if (!noAssert) checkOffset(offset, 1, this.length)
|
2883 | if (!(this[offset] & 0x80)) return (this[offset])
|
2884 | return ((0xff - this[offset] + 1) * -1)
|
2885 | }
|
2886 |
|
2887 | Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
|
2888 | if (!noAssert) checkOffset(offset, 2, this.length)
|
2889 | var val = this[offset] | (this[offset + 1] << 8)
|
2890 | return (val & 0x8000) ? val | 0xFFFF0000 : val
|
2891 | }
|
2892 |
|
2893 | Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
|
2894 | if (!noAssert) checkOffset(offset, 2, this.length)
|
2895 | var val = this[offset + 1] | (this[offset] << 8)
|
2896 | return (val & 0x8000) ? val | 0xFFFF0000 : val
|
2897 | }
|
2898 |
|
2899 | Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
|
2900 | if (!noAssert) checkOffset(offset, 4, this.length)
|
2901 |
|
2902 | return (this[offset]) |
|
2903 | (this[offset + 1] << 8) |
|
2904 | (this[offset + 2] << 16) |
|
2905 | (this[offset + 3] << 24)
|
2906 | }
|
2907 |
|
2908 | Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
|
2909 | if (!noAssert) checkOffset(offset, 4, this.length)
|
2910 |
|
2911 | return (this[offset] << 24) |
|
2912 | (this[offset + 1] << 16) |
|
2913 | (this[offset + 2] << 8) |
|
2914 | (this[offset + 3])
|
2915 | }
|
2916 |
|
2917 | Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
|
2918 | if (!noAssert) checkOffset(offset, 4, this.length)
|
2919 | return ieee754.read(this, offset, true, 23, 4)
|
2920 | }
|
2921 |
|
2922 | Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
|
2923 | if (!noAssert) checkOffset(offset, 4, this.length)
|
2924 | return ieee754.read(this, offset, false, 23, 4)
|
2925 | }
|
2926 |
|
2927 | Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
|
2928 | if (!noAssert) checkOffset(offset, 8, this.length)
|
2929 | return ieee754.read(this, offset, true, 52, 8)
|
2930 | }
|
2931 |
|
2932 | Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
|
2933 | if (!noAssert) checkOffset(offset, 8, this.length)
|
2934 | return ieee754.read(this, offset, false, 52, 8)
|
2935 | }
|
2936 |
|
2937 | function checkInt (buf, value, offset, ext, max, min) {
|
2938 | if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
|
2939 | if (value > max || value < min) throw new RangeError('value is out of bounds')
|
2940 | if (offset + ext > buf.length) throw new RangeError('index out of range')
|
2941 | }
|
2942 |
|
2943 | Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
|
2944 | value = +value
|
2945 | offset = offset | 0
|
2946 | byteLength = byteLength | 0
|
2947 | if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
|
2948 |
|
2949 | var mul = 1
|
2950 | var i = 0
|
2951 | this[offset] = value & 0xFF
|
2952 | while (++i < byteLength && (mul *= 0x100)) {
|
2953 | this[offset + i] = (value / mul) & 0xFF
|
2954 | }
|
2955 |
|
2956 | return offset + byteLength
|
2957 | }
|
2958 |
|
2959 | Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
|
2960 | value = +value
|
2961 | offset = offset | 0
|
2962 | byteLength = byteLength | 0
|
2963 | if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
|
2964 |
|
2965 | var i = byteLength - 1
|
2966 | var mul = 1
|
2967 | this[offset + i] = value & 0xFF
|
2968 | while (--i >= 0 && (mul *= 0x100)) {
|
2969 | this[offset + i] = (value / mul) & 0xFF
|
2970 | }
|
2971 |
|
2972 | return offset + byteLength
|
2973 | }
|
2974 |
|
2975 | Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
|
2976 | value = +value
|
2977 | offset = offset | 0
|
2978 | if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
|
2979 | if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
|
2980 | this[offset] = value
|
2981 | return offset + 1
|
2982 | }
|
2983 |
|
2984 | function objectWriteUInt16 (buf, value, offset, littleEndian) {
|
2985 | if (value < 0) value = 0xffff + value + 1
|
2986 | for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
|
2987 | buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
|
2988 | (littleEndian ? i : 1 - i) * 8
|
2989 | }
|
2990 | }
|
2991 |
|
2992 | Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
|
2993 | value = +value
|
2994 | offset = offset | 0
|
2995 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
|
2996 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
2997 | this[offset] = value
|
2998 | this[offset + 1] = (value >>> 8)
|
2999 | } else {
|
3000 | objectWriteUInt16(this, value, offset, true)
|
3001 | }
|
3002 | return offset + 2
|
3003 | }
|
3004 |
|
3005 | Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
|
3006 | value = +value
|
3007 | offset = offset | 0
|
3008 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
|
3009 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
3010 | this[offset] = (value >>> 8)
|
3011 | this[offset + 1] = value
|
3012 | } else {
|
3013 | objectWriteUInt16(this, value, offset, false)
|
3014 | }
|
3015 | return offset + 2
|
3016 | }
|
3017 |
|
3018 | function objectWriteUInt32 (buf, value, offset, littleEndian) {
|
3019 | if (value < 0) value = 0xffffffff + value + 1
|
3020 | for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
|
3021 | buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
|
3022 | }
|
3023 | }
|
3024 |
|
3025 | Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
|
3026 | value = +value
|
3027 | offset = offset | 0
|
3028 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
|
3029 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
3030 | this[offset + 3] = (value >>> 24)
|
3031 | this[offset + 2] = (value >>> 16)
|
3032 | this[offset + 1] = (value >>> 8)
|
3033 | this[offset] = value
|
3034 | } else {
|
3035 | objectWriteUInt32(this, value, offset, true)
|
3036 | }
|
3037 | return offset + 4
|
3038 | }
|
3039 |
|
3040 | Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
|
3041 | value = +value
|
3042 | offset = offset | 0
|
3043 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
|
3044 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
3045 | this[offset] = (value >>> 24)
|
3046 | this[offset + 1] = (value >>> 16)
|
3047 | this[offset + 2] = (value >>> 8)
|
3048 | this[offset + 3] = value
|
3049 | } else {
|
3050 | objectWriteUInt32(this, value, offset, false)
|
3051 | }
|
3052 | return offset + 4
|
3053 | }
|
3054 |
|
3055 | Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
|
3056 | value = +value
|
3057 | offset = offset | 0
|
3058 | if (!noAssert) {
|
3059 | var limit = Math.pow(2, 8 * byteLength - 1)
|
3060 |
|
3061 | checkInt(this, value, offset, byteLength, limit - 1, -limit)
|
3062 | }
|
3063 |
|
3064 | var i = 0
|
3065 | var mul = 1
|
3066 | var sub = value < 0 ? 1 : 0
|
3067 | this[offset] = value & 0xFF
|
3068 | while (++i < byteLength && (mul *= 0x100)) {
|
3069 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
|
3070 | }
|
3071 |
|
3072 | return offset + byteLength
|
3073 | }
|
3074 |
|
3075 | Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
|
3076 | value = +value
|
3077 | offset = offset | 0
|
3078 | if (!noAssert) {
|
3079 | var limit = Math.pow(2, 8 * byteLength - 1)
|
3080 |
|
3081 | checkInt(this, value, offset, byteLength, limit - 1, -limit)
|
3082 | }
|
3083 |
|
3084 | var i = byteLength - 1
|
3085 | var mul = 1
|
3086 | var sub = value < 0 ? 1 : 0
|
3087 | this[offset + i] = value & 0xFF
|
3088 | while (--i >= 0 && (mul *= 0x100)) {
|
3089 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
|
3090 | }
|
3091 |
|
3092 | return offset + byteLength
|
3093 | }
|
3094 |
|
3095 | Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
|
3096 | value = +value
|
3097 | offset = offset | 0
|
3098 | if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
|
3099 | if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
|
3100 | if (value < 0) value = 0xff + value + 1
|
3101 | this[offset] = value
|
3102 | return offset + 1
|
3103 | }
|
3104 |
|
3105 | Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
|
3106 | value = +value
|
3107 | offset = offset | 0
|
3108 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
|
3109 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
3110 | this[offset] = value
|
3111 | this[offset + 1] = (value >>> 8)
|
3112 | } else {
|
3113 | objectWriteUInt16(this, value, offset, true)
|
3114 | }
|
3115 | return offset + 2
|
3116 | }
|
3117 |
|
3118 | Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
|
3119 | value = +value
|
3120 | offset = offset | 0
|
3121 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
|
3122 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
3123 | this[offset] = (value >>> 8)
|
3124 | this[offset + 1] = value
|
3125 | } else {
|
3126 | objectWriteUInt16(this, value, offset, false)
|
3127 | }
|
3128 | return offset + 2
|
3129 | }
|
3130 |
|
3131 | Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
|
3132 | value = +value
|
3133 | offset = offset | 0
|
3134 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
|
3135 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
3136 | this[offset] = value
|
3137 | this[offset + 1] = (value >>> 8)
|
3138 | this[offset + 2] = (value >>> 16)
|
3139 | this[offset + 3] = (value >>> 24)
|
3140 | } else {
|
3141 | objectWriteUInt32(this, value, offset, true)
|
3142 | }
|
3143 | return offset + 4
|
3144 | }
|
3145 |
|
3146 | Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
|
3147 | value = +value
|
3148 | offset = offset | 0
|
3149 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
|
3150 | if (value < 0) value = 0xffffffff + value + 1
|
3151 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
3152 | this[offset] = (value >>> 24)
|
3153 | this[offset + 1] = (value >>> 16)
|
3154 | this[offset + 2] = (value >>> 8)
|
3155 | this[offset + 3] = value
|
3156 | } else {
|
3157 | objectWriteUInt32(this, value, offset, false)
|
3158 | }
|
3159 | return offset + 4
|
3160 | }
|
3161 |
|
3162 | function checkIEEE754 (buf, value, offset, ext, max, min) {
|
3163 | if (value > max || value < min) throw new RangeError('value is out of bounds')
|
3164 | if (offset + ext > buf.length) throw new RangeError('index out of range')
|
3165 | if (offset < 0) throw new RangeError('index out of range')
|
3166 | }
|
3167 |
|
3168 | function writeFloat (buf, value, offset, littleEndian, noAssert) {
|
3169 | if (!noAssert) {
|
3170 | checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
|
3171 | }
|
3172 | ieee754.write(buf, value, offset, littleEndian, 23, 4)
|
3173 | return offset + 4
|
3174 | }
|
3175 |
|
3176 | Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
|
3177 | return writeFloat(this, value, offset, true, noAssert)
|
3178 | }
|
3179 |
|
3180 | Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
|
3181 | return writeFloat(this, value, offset, false, noAssert)
|
3182 | }
|
3183 |
|
3184 | function writeDouble (buf, value, offset, littleEndian, noAssert) {
|
3185 | if (!noAssert) {
|
3186 | checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
|
3187 | }
|
3188 | ieee754.write(buf, value, offset, littleEndian, 52, 8)
|
3189 | return offset + 8
|
3190 | }
|
3191 |
|
3192 | Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
|
3193 | return writeDouble(this, value, offset, true, noAssert)
|
3194 | }
|
3195 |
|
3196 | Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
|
3197 | return writeDouble(this, value, offset, false, noAssert)
|
3198 | }
|
3199 |
|
3200 | // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
|
3201 | Buffer.prototype.copy = function copy (target, targetStart, start, end) {
|
3202 | if (!start) start = 0
|
3203 | if (!end && end !== 0) end = this.length
|
3204 | if (targetStart >= target.length) targetStart = target.length
|
3205 | if (!targetStart) targetStart = 0
|
3206 | if (end > 0 && end < start) end = start
|
3207 |
|
3208 | // Copy 0 bytes; we're done
|
3209 | if (end === start) return 0
|
3210 | if (target.length === 0 || this.length === 0) return 0
|
3211 |
|
3212 | // Fatal error conditions
|
3213 | if (targetStart < 0) {
|
3214 | throw new RangeError('targetStart out of bounds')
|
3215 | }
|
3216 | if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
|
3217 | if (end < 0) throw new RangeError('sourceEnd out of bounds')
|
3218 |
|
3219 | // Are we oob?
|
3220 | if (end > this.length) end = this.length
|
3221 | if (target.length - targetStart < end - start) {
|
3222 | end = target.length - targetStart + start
|
3223 | }
|
3224 |
|
3225 | var len = end - start
|
3226 | var i
|
3227 |
|
3228 | if (this === target && start < targetStart && targetStart < end) {
|
3229 | // descending copy from end
|
3230 | for (i = len - 1; i >= 0; i--) {
|
3231 | target[i + targetStart] = this[i + start]
|
3232 | }
|
3233 | } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
|
3234 | // ascending copy from start
|
3235 | for (i = 0; i < len; i++) {
|
3236 | target[i + targetStart] = this[i + start]
|
3237 | }
|
3238 | } else {
|
3239 | target._set(this.subarray(start, start + len), targetStart)
|
3240 | }
|
3241 |
|
3242 | return len
|
3243 | }
|
3244 |
|
3245 | // fill(value, start=0, end=buffer.length)
|
3246 | Buffer.prototype.fill = function fill (value, start, end) {
|
3247 | if (!value) value = 0
|
3248 | if (!start) start = 0
|
3249 | if (!end) end = this.length
|
3250 |
|
3251 | if (end < start) throw new RangeError('end < start')
|
3252 |
|
3253 | // Fill 0 bytes; we're done
|
3254 | if (end === start) return
|
3255 | if (this.length === 0) return
|
3256 |
|
3257 | if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
|
3258 | if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
|
3259 |
|
3260 | var i
|
3261 | if (typeof value === 'number') {
|
3262 | for (i = start; i < end; i++) {
|
3263 | this[i] = value
|
3264 | }
|
3265 | } else {
|
3266 | var bytes = utf8ToBytes(value.toString())
|
3267 | var len = bytes.length
|
3268 | for (i = start; i < end; i++) {
|
3269 | this[i] = bytes[i % len]
|
3270 | }
|
3271 | }
|
3272 |
|
3273 | return this
|
3274 | }
|
3275 |
|
3276 | /**
|
3277 | * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
|
3278 | * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
|
3279 | */
|
3280 | Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
|
3281 | if (typeof Uint8Array !== 'undefined') {
|
3282 | if (Buffer.TYPED_ARRAY_SUPPORT) {
|
3283 | return (new Buffer(this)).buffer
|
3284 | } else {
|
3285 | var buf = new Uint8Array(this.length)
|
3286 | for (var i = 0, len = buf.length; i < len; i += 1) {
|
3287 | buf[i] = this[i]
|
3288 | }
|
3289 | return buf.buffer
|
3290 | }
|
3291 | } else {
|
3292 | throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
|
3293 | }
|
3294 | }
|
3295 |
|
3296 | // HELPER FUNCTIONS
|
3297 | // ================
|
3298 |
|
3299 | var BP = Buffer.prototype
|
3300 |
|
3301 | /**
|
3302 | * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
|
3303 | */
|
3304 | Buffer._augment = function _augment (arr) {
|
3305 | arr.constructor = Buffer
|
3306 | arr._isBuffer = true
|
3307 |
|
3308 | // save reference to original Uint8Array set method before overwriting
|
3309 | arr._set = arr.set
|
3310 |
|
3311 | // deprecated
|
3312 | arr.get = BP.get
|
3313 | arr.set = BP.set
|
3314 |
|
3315 | arr.write = BP.write
|
3316 | arr.toString = BP.toString
|
3317 | arr.toLocaleString = BP.toString
|
3318 | arr.toJSON = BP.toJSON
|
3319 | arr.equals = BP.equals
|
3320 | arr.compare = BP.compare
|
3321 | arr.indexOf = BP.indexOf
|
3322 | arr.copy = BP.copy
|
3323 | arr.slice = BP.slice
|
3324 | arr.readUIntLE = BP.readUIntLE
|
3325 | arr.readUIntBE = BP.readUIntBE
|
3326 | arr.readUInt8 = BP.readUInt8
|
3327 | arr.readUInt16LE = BP.readUInt16LE
|
3328 | arr.readUInt16BE = BP.readUInt16BE
|
3329 | arr.readUInt32LE = BP.readUInt32LE
|
3330 | arr.readUInt32BE = BP.readUInt32BE
|
3331 | arr.readIntLE = BP.readIntLE
|
3332 | arr.readIntBE = BP.readIntBE
|
3333 | arr.readInt8 = BP.readInt8
|
3334 | arr.readInt16LE = BP.readInt16LE
|
3335 | arr.readInt16BE = BP.readInt16BE
|
3336 | arr.readInt32LE = BP.readInt32LE
|
3337 | arr.readInt32BE = BP.readInt32BE
|
3338 | arr.readFloatLE = BP.readFloatLE
|
3339 | arr.readFloatBE = BP.readFloatBE
|
3340 | arr.readDoubleLE = BP.readDoubleLE
|
3341 | arr.readDoubleBE = BP.readDoubleBE
|
3342 | arr.writeUInt8 = BP.writeUInt8
|
3343 | arr.writeUIntLE = BP.writeUIntLE
|
3344 | arr.writeUIntBE = BP.writeUIntBE
|
3345 | arr.writeUInt16LE = BP.writeUInt16LE
|
3346 | arr.writeUInt16BE = BP.writeUInt16BE
|
3347 | arr.writeUInt32LE = BP.writeUInt32LE
|
3348 | arr.writeUInt32BE = BP.writeUInt32BE
|
3349 | arr.writeIntLE = BP.writeIntLE
|
3350 | arr.writeIntBE = BP.writeIntBE
|
3351 | arr.writeInt8 = BP.writeInt8
|
3352 | arr.writeInt16LE = BP.writeInt16LE
|
3353 | arr.writeInt16BE = BP.writeInt16BE
|
3354 | arr.writeInt32LE = BP.writeInt32LE
|
3355 | arr.writeInt32BE = BP.writeInt32BE
|
3356 | arr.writeFloatLE = BP.writeFloatLE
|
3357 | arr.writeFloatBE = BP.writeFloatBE
|
3358 | arr.writeDoubleLE = BP.writeDoubleLE
|
3359 | arr.writeDoubleBE = BP.writeDoubleBE
|
3360 | arr.fill = BP.fill
|
3361 | arr.inspect = BP.inspect
|
3362 | arr.toArrayBuffer = BP.toArrayBuffer
|
3363 |
|
3364 | return arr
|
3365 | }
|
3366 |
|
3367 | var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
|
3368 |
|
3369 | function base64clean (str) {
|
3370 | // Node strips out invalid characters like \n and \t from the string, base64-js does not
|
3371 | str = stringtrim(str).replace(INVALID_BASE64_RE, '')
|
3372 | // Node converts strings with length < 2 to ''
|
3373 | if (str.length < 2) return ''
|
3374 | // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
|
3375 | while (str.length % 4 !== 0) {
|
3376 | str = str + '='
|
3377 | }
|
3378 | return str
|
3379 | }
|
3380 |
|
3381 | function stringtrim (str) {
|
3382 | if (str.trim) return str.trim()
|
3383 | return str.replace(/^\s+|\s+$/g, '')
|
3384 | }
|
3385 |
|
3386 | function toHex (n) {
|
3387 | if (n < 16) return '0' + n.toString(16)
|
3388 | return n.toString(16)
|
3389 | }
|
3390 |
|
3391 | function utf8ToBytes (string, units) {
|
3392 | units = units || Infinity
|
3393 | var codePoint
|
3394 | var length = string.length
|
3395 | var leadSurrogate = null
|
3396 | var bytes = []
|
3397 |
|
3398 | for (var i = 0; i < length; i++) {
|
3399 | codePoint = string.charCodeAt(i)
|
3400 |
|
3401 | // is surrogate component
|
3402 | if (codePoint > 0xD7FF && codePoint < 0xE000) {
|
3403 | // last char was a lead
|
3404 | if (!leadSurrogate) {
|
3405 | // no lead yet
|
3406 | if (codePoint > 0xDBFF) {
|
3407 | // unexpected trail
|
3408 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
|
3409 | continue
|
3410 | } else if (i + 1 === length) {
|
3411 | // unpaired lead
|
3412 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
|
3413 | continue
|
3414 | }
|
3415 |
|
3416 | // valid lead
|
3417 | leadSurrogate = codePoint
|
3418 |
|
3419 | continue
|
3420 | }
|
3421 |
|
3422 | // 2 leads in a row
|
3423 | if (codePoint < 0xDC00) {
|
3424 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
|
3425 | leadSurrogate = codePoint
|
3426 | continue
|
3427 | }
|
3428 |
|
3429 | // valid surrogate pair
|
3430 | codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
|
3431 | } else if (leadSurrogate) {
|
3432 | // valid bmp char, but last char was a lead
|
3433 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
|
3434 | }
|
3435 |
|
3436 | leadSurrogate = null
|
3437 |
|
3438 | // encode utf8
|
3439 | if (codePoint < 0x80) {
|
3440 | if ((units -= 1) < 0) break
|
3441 | bytes.push(codePoint)
|
3442 | } else if (codePoint < 0x800) {
|
3443 | if ((units -= 2) < 0) break
|
3444 | bytes.push(
|
3445 | codePoint >> 0x6 | 0xC0,
|
3446 | codePoint & 0x3F | 0x80
|
3447 | )
|
3448 | } else if (codePoint < 0x10000) {
|
3449 | if ((units -= 3) < 0) break
|
3450 | bytes.push(
|
3451 | codePoint >> 0xC | 0xE0,
|
3452 | codePoint >> 0x6 & 0x3F | 0x80,
|
3453 | codePoint & 0x3F | 0x80
|
3454 | )
|
3455 | } else if (codePoint < 0x110000) {
|
3456 | if ((units -= 4) < 0) break
|
3457 | bytes.push(
|
3458 | codePoint >> 0x12 | 0xF0,
|
3459 | codePoint >> 0xC & 0x3F | 0x80,
|
3460 | codePoint >> 0x6 & 0x3F | 0x80,
|
3461 | codePoint & 0x3F | 0x80
|
3462 | )
|
3463 | } else {
|
3464 | throw new Error('Invalid code point')
|
3465 | }
|
3466 | }
|
3467 |
|
3468 | return bytes
|
3469 | }
|
3470 |
|
3471 | function asciiToBytes (str) {
|
3472 | var byteArray = []
|
3473 | for (var i = 0; i < str.length; i++) {
|
3474 | // Node's code seems to be doing this and not & 0x7F..
|
3475 | byteArray.push(str.charCodeAt(i) & 0xFF)
|
3476 | }
|
3477 | return byteArray
|
3478 | }
|
3479 |
|
3480 | function utf16leToBytes (str, units) {
|
3481 | var c, hi, lo
|
3482 | var byteArray = []
|
3483 | for (var i = 0; i < str.length; i++) {
|
3484 | if ((units -= 2) < 0) break
|
3485 |
|
3486 | c = str.charCodeAt(i)
|
3487 | hi = c >> 8
|
3488 | lo = c % 256
|
3489 | byteArray.push(lo)
|
3490 | byteArray.push(hi)
|
3491 | }
|
3492 |
|
3493 | return byteArray
|
3494 | }
|
3495 |
|
3496 | function base64ToBytes (str) {
|
3497 | return base64.toByteArray(base64clean(str))
|
3498 | }
|
3499 |
|
3500 | function blitBuffer (src, dst, offset, length) {
|
3501 | for (var i = 0; i < length; i++) {
|
3502 | if ((i + offset >= dst.length) || (i >= src.length)) break
|
3503 | dst[i + offset] = src[i]
|
3504 | }
|
3505 | return i
|
3506 | }
|
3507 |
|
3508 | },{"base64-js":6,"ieee754":7,"is-array":8}],6:[function(require,module,exports){
|
3509 | var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
3510 |
|
3511 | ;(function (exports) {
|
3512 | 'use strict';
|
3513 |
|
3514 | var Arr = (typeof Uint8Array !== 'undefined')
|
3515 | ? Uint8Array
|
3516 | : Array
|
3517 |
|
3518 | var PLUS = '+'.charCodeAt(0)
|
3519 | var SLASH = '/'.charCodeAt(0)
|
3520 | var NUMBER = '0'.charCodeAt(0)
|
3521 | var LOWER = 'a'.charCodeAt(0)
|
3522 | var UPPER = 'A'.charCodeAt(0)
|
3523 | var PLUS_URL_SAFE = '-'.charCodeAt(0)
|
3524 | var SLASH_URL_SAFE = '_'.charCodeAt(0)
|
3525 |
|
3526 | function decode (elt) {
|
3527 | var code = elt.charCodeAt(0)
|
3528 | if (code === PLUS ||
|
3529 | code === PLUS_URL_SAFE)
|
3530 | return 62 // '+'
|
3531 | if (code === SLASH ||
|
3532 | code === SLASH_URL_SAFE)
|
3533 | return 63 // '/'
|
3534 | if (code < NUMBER)
|
3535 | return -1 //no match
|
3536 | if (code < NUMBER + 10)
|
3537 | return code - NUMBER + 26 + 26
|
3538 | if (code < UPPER + 26)
|
3539 | return code - UPPER
|
3540 | if (code < LOWER + 26)
|
3541 | return code - LOWER + 26
|
3542 | }
|
3543 |
|
3544 | function b64ToByteArray (b64) {
|
3545 | var i, j, l, tmp, placeHolders, arr
|
3546 |
|
3547 | if (b64.length % 4 > 0) {
|
3548 | throw new Error('Invalid string. Length must be a multiple of 4')
|
3549 | }
|
3550 |
|
3551 | // the number of equal signs (place holders)
|
3552 | // if there are two placeholders, than the two characters before it
|
3553 | // represent one byte
|
3554 | // if there is only one, then the three characters before it represent 2 bytes
|
3555 | // this is just a cheap hack to not do indexOf twice
|
3556 | var len = b64.length
|
3557 | placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
|
3558 |
|
3559 | // base64 is 4/3 + up to two characters of the original data
|
3560 | arr = new Arr(b64.length * 3 / 4 - placeHolders)
|
3561 |
|
3562 | // if there are placeholders, only get up to the last complete 4 chars
|
3563 | l = placeHolders > 0 ? b64.length - 4 : b64.length
|
3564 |
|
3565 | var L = 0
|
3566 |
|
3567 | function push (v) {
|
3568 | arr[L++] = v
|
3569 | }
|
3570 |
|
3571 | for (i = 0, j = 0; i < l; i += 4, j += 3) {
|
3572 | tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
|
3573 | push((tmp & 0xFF0000) >> 16)
|
3574 | push((tmp & 0xFF00) >> 8)
|
3575 | push(tmp & 0xFF)
|
3576 | }
|
3577 |
|
3578 | if (placeHolders === 2) {
|
3579 | tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
|
3580 | push(tmp & 0xFF)
|
3581 | } else if (placeHolders === 1) {
|
3582 | tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
|
3583 | push((tmp >> 8) & 0xFF)
|
3584 | push(tmp & 0xFF)
|
3585 | }
|
3586 |
|
3587 | return arr
|
3588 | }
|
3589 |
|
3590 | function uint8ToBase64 (uint8) {
|
3591 | var i,
|
3592 | extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
|
3593 | output = "",
|
3594 | temp, length
|
3595 |
|
3596 | function encode (num) {
|
3597 | return lookup.charAt(num)
|
3598 | }
|
3599 |
|
3600 | function tripletToBase64 (num) {
|
3601 | return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
|
3602 | }
|
3603 |
|
3604 | // go through the array every three bytes, we'll deal with trailing stuff later
|
3605 | for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
|
3606 | temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
|
3607 | output += tripletToBase64(temp)
|
3608 | }
|
3609 |
|
3610 | // pad the end with zeros, but make sure to not forget the extra bytes
|
3611 | switch (extraBytes) {
|
3612 | case 1:
|
3613 | temp = uint8[uint8.length - 1]
|
3614 | output += encode(temp >> 2)
|
3615 | output += encode((temp << 4) & 0x3F)
|
3616 | output += '=='
|
3617 | break
|
3618 | case 2:
|
3619 | temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
|
3620 | output += encode(temp >> 10)
|
3621 | output += encode((temp >> 4) & 0x3F)
|
3622 | output += encode((temp << 2) & 0x3F)
|
3623 | output += '='
|
3624 | break
|
3625 | }
|
3626 |
|
3627 | return output
|
3628 | }
|
3629 |
|
3630 | exports.toByteArray = b64ToByteArray
|
3631 | exports.fromByteArray = uint8ToBase64
|
3632 | }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
|
3633 |
|
3634 | },{}],7:[function(require,module,exports){
|
3635 | exports.read = function (buffer, offset, isLE, mLen, nBytes) {
|
3636 | var e, m
|
3637 | var eLen = nBytes * 8 - mLen - 1
|
3638 | var eMax = (1 << eLen) - 1
|
3639 | var eBias = eMax >> 1
|
3640 | var nBits = -7
|
3641 | var i = isLE ? (nBytes - 1) : 0
|
3642 | var d = isLE ? -1 : 1
|
3643 | var s = buffer[offset + i]
|
3644 |
|
3645 | i += d
|
3646 |
|
3647 | e = s & ((1 << (-nBits)) - 1)
|
3648 | s >>= (-nBits)
|
3649 | nBits += eLen
|
3650 | for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
|
3651 |
|
3652 | m = e & ((1 << (-nBits)) - 1)
|
3653 | e >>= (-nBits)
|
3654 | nBits += mLen
|
3655 | for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
|
3656 |
|
3657 | if (e === 0) {
|
3658 | e = 1 - eBias
|
3659 | } else if (e === eMax) {
|
3660 | return m ? NaN : ((s ? -1 : 1) * Infinity)
|
3661 | } else {
|
3662 | m = m + Math.pow(2, mLen)
|
3663 | e = e - eBias
|
3664 | }
|
3665 | return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
|
3666 | }
|
3667 |
|
3668 | exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
|
3669 | var e, m, c
|
3670 | var eLen = nBytes * 8 - mLen - 1
|
3671 | var eMax = (1 << eLen) - 1
|
3672 | var eBias = eMax >> 1
|
3673 | var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
|
3674 | var i = isLE ? 0 : (nBytes - 1)
|
3675 | var d = isLE ? 1 : -1
|
3676 | var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
|
3677 |
|
3678 | value = Math.abs(value)
|
3679 |
|
3680 | if (isNaN(value) || value === Infinity) {
|
3681 | m = isNaN(value) ? 1 : 0
|
3682 | e = eMax
|
3683 | } else {
|
3684 | e = Math.floor(Math.log(value) / Math.LN2)
|
3685 | if (value * (c = Math.pow(2, -e)) < 1) {
|
3686 | e--
|
3687 | c *= 2
|
3688 | }
|
3689 | if (e + eBias >= 1) {
|
3690 | value += rt / c
|
3691 | } else {
|
3692 | value += rt * Math.pow(2, 1 - eBias)
|
3693 | }
|
3694 | if (value * c >= 2) {
|
3695 | e++
|
3696 | c /= 2
|
3697 | }
|
3698 |
|
3699 | if (e + eBias >= eMax) {
|
3700 | m = 0
|
3701 | e = eMax
|
3702 | } else if (e + eBias >= 1) {
|
3703 | m = (value * c - 1) * Math.pow(2, mLen)
|
3704 | e = e + eBias
|
3705 | } else {
|
3706 | m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
|
3707 | e = 0
|
3708 | }
|
3709 | }
|
3710 |
|
3711 | for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
|
3712 |
|
3713 | e = (e << mLen) | m
|
3714 | eLen += mLen
|
3715 | for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
|
3716 |
|
3717 | buffer[offset + i - d] |= s * 128
|
3718 | }
|
3719 |
|
3720 | },{}],8:[function(require,module,exports){
|
3721 |
|
3722 | /**
|
3723 | * isArray
|
3724 | */
|
3725 |
|
3726 | var isArray = Array.isArray;
|
3727 |
|
3728 | /**
|
3729 | * toString
|
3730 | */
|
3731 |
|
3732 | var str = Object.prototype.toString;
|
3733 |
|
3734 | /**
|
3735 | * Whether or not the given `val`
|
3736 | * is an array.
|
3737 | *
|
3738 | * example:
|
3739 | *
|
3740 | * isArray([]);
|
3741 | * // > true
|
3742 | * isArray(arguments);
|
3743 | * // > false
|
3744 | * isArray('');
|
3745 | * // > false
|
3746 | *
|
3747 | * @param {mixed} val
|
3748 | * @return {bool}
|
3749 | */
|
3750 |
|
3751 | module.exports = isArray || function (val) {
|
3752 | return !! val && '[object Array]' == str.call(val);
|
3753 | };
|
3754 |
|
3755 | },{}],9:[function(require,module,exports){
|
3756 | // shim for using process in browser
|
3757 |
|
3758 | var process = module.exports = {};
|
3759 | var queue = [];
|
3760 | var draining = false;
|
3761 | var currentQueue;
|
3762 | var queueIndex = -1;
|
3763 |
|
3764 | function cleanUpNextTick() {
|
3765 | draining = false;
|
3766 | if (currentQueue.length) {
|
3767 | queue = currentQueue.concat(queue);
|
3768 | } else {
|
3769 | queueIndex = -1;
|
3770 | }
|
3771 | if (queue.length) {
|
3772 | drainQueue();
|
3773 | }
|
3774 | }
|
3775 |
|
3776 | function drainQueue() {
|
3777 | if (draining) {
|
3778 | return;
|
3779 | }
|
3780 | var timeout = setTimeout(cleanUpNextTick);
|
3781 | draining = true;
|
3782 |
|
3783 | var len = queue.length;
|
3784 | while(len) {
|
3785 | currentQueue = queue;
|
3786 | queue = [];
|
3787 | while (++queueIndex < len) {
|
3788 | currentQueue[queueIndex].run();
|
3789 | }
|
3790 | queueIndex = -1;
|
3791 | len = queue.length;
|
3792 | }
|
3793 | currentQueue = null;
|
3794 | draining = false;
|
3795 | clearTimeout(timeout);
|
3796 | }
|
3797 |
|
3798 | process.nextTick = function (fun) {
|
3799 | var args = new Array(arguments.length - 1);
|
3800 | if (arguments.length > 1) {
|
3801 | for (var i = 1; i < arguments.length; i++) {
|
3802 | args[i - 1] = arguments[i];
|
3803 | }
|
3804 | }
|
3805 | queue.push(new Item(fun, args));
|
3806 | if (queue.length === 1 && !draining) {
|
3807 | setTimeout(drainQueue, 0);
|
3808 | }
|
3809 | };
|
3810 |
|
3811 | // v8 likes predictible objects
|
3812 | function Item(fun, array) {
|
3813 | this.fun = fun;
|
3814 | this.array = array;
|
3815 | }
|
3816 | Item.prototype.run = function () {
|
3817 | this.fun.apply(null, this.array);
|
3818 | };
|
3819 | process.title = 'browser';
|
3820 | process.browser = true;
|
3821 | process.env = {};
|
3822 | process.argv = [];
|
3823 | process.version = ''; // empty string to avoid regexp issues
|
3824 | process.versions = {};
|
3825 |
|
3826 | function noop() {}
|
3827 |
|
3828 | process.on = noop;
|
3829 | process.addListener = noop;
|
3830 | process.once = noop;
|
3831 | process.off = noop;
|
3832 | process.removeListener = noop;
|
3833 | process.removeAllListeners = noop;
|
3834 | process.emit = noop;
|
3835 |
|
3836 | process.binding = function (name) {
|
3837 | throw new Error('process.binding is not supported');
|
3838 | };
|
3839 |
|
3840 | // TODO(shtylman)
|
3841 | process.cwd = function () { return '/' };
|
3842 | process.chdir = function (dir) {
|
3843 | throw new Error('process.chdir is not supported');
|
3844 | };
|
3845 | process.umask = function() { return 0; };
|
3846 |
|
3847 | },{}],10:[function(require,module,exports){
|
3848 | (function (global){
|
3849 | /**
|
3850 | * @license
|
3851 | * lodash 3.10.1 (Custom Build) <https://lodash.com/>
|
3852 | * Build: `lodash modern -d -o ./index.js`
|
3853 | * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
|
3854 | * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
|
3855 | * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
3856 | * Available under MIT license <https://lodash.com/license>
|
3857 | */
|
3858 | ;(function() {
|
3859 |
|
3860 | /** Used as a safe reference for `undefined` in pre-ES5 environments. */
|
3861 | var undefined;
|
3862 |
|
3863 | /** Used as the semantic version number. */
|
3864 | var VERSION = '3.10.1';
|
3865 |
|
3866 | /** Used to compose bitmasks for wrapper metadata. */
|
3867 | var BIND_FLAG = 1,
|
3868 | BIND_KEY_FLAG = 2,
|
3869 | CURRY_BOUND_FLAG = 4,
|
3870 | CURRY_FLAG = 8,
|
3871 | CURRY_RIGHT_FLAG = 16,
|
3872 | PARTIAL_FLAG = 32,
|
3873 | PARTIAL_RIGHT_FLAG = 64,
|
3874 | ARY_FLAG = 128,
|
3875 | REARG_FLAG = 256;
|
3876 |
|
3877 | /** Used as default options for `_.trunc`. */
|
3878 | var DEFAULT_TRUNC_LENGTH = 30,
|
3879 | DEFAULT_TRUNC_OMISSION = '...';
|
3880 |
|
3881 | /** Used to detect when a function becomes hot. */
|
3882 | var HOT_COUNT = 150,
|
3883 | HOT_SPAN = 16;
|
3884 |
|
3885 | /** Used as the size to enable large array optimizations. */
|
3886 | var LARGE_ARRAY_SIZE = 200;
|
3887 |
|
3888 | /** Used to indicate the type of lazy iteratees. */
|
3889 | var LAZY_FILTER_FLAG = 1,
|
3890 | LAZY_MAP_FLAG = 2;
|
3891 |
|
3892 | /** Used as the `TypeError` message for "Functions" methods. */
|
3893 | var FUNC_ERROR_TEXT = 'Expected a function';
|
3894 |
|
3895 | /** Used as the internal argument placeholder. */
|
3896 | var PLACEHOLDER = '__lodash_placeholder__';
|
3897 |
|
3898 | /** `Object#toString` result references. */
|
3899 | var argsTag = '[object Arguments]',
|
3900 | arrayTag = '[object Array]',
|
3901 | boolTag = '[object Boolean]',
|
3902 | dateTag = '[object Date]',
|
3903 | errorTag = '[object Error]',
|
3904 | funcTag = '[object Function]',
|
3905 | mapTag = '[object Map]',
|
3906 | numberTag = '[object Number]',
|
3907 | objectTag = '[object Object]',
|
3908 | regexpTag = '[object RegExp]',
|
3909 | setTag = '[object Set]',
|
3910 | stringTag = '[object String]',
|
3911 | weakMapTag = '[object WeakMap]';
|
3912 |
|
3913 | var arrayBufferTag = '[object ArrayBuffer]',
|
3914 | float32Tag = '[object Float32Array]',
|
3915 | float64Tag = '[object Float64Array]',
|
3916 | int8Tag = '[object Int8Array]',
|
3917 | int16Tag = '[object Int16Array]',
|
3918 | int32Tag = '[object Int32Array]',
|
3919 | uint8Tag = '[object Uint8Array]',
|
3920 | uint8ClampedTag = '[object Uint8ClampedArray]',
|
3921 | uint16Tag = '[object Uint16Array]',
|
3922 | uint32Tag = '[object Uint32Array]';
|
3923 |
|
3924 | /** Used to match empty string literals in compiled template source. */
|
3925 | var reEmptyStringLeading = /\b__p \+= '';/g,
|
3926 | reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
|
3927 | reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
|
3928 |
|
3929 | /** Used to match HTML entities and HTML characters. */
|
3930 | var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
|
3931 | reUnescapedHtml = /[&<>"'`]/g,
|
3932 | reHasEscapedHtml = RegExp(reEscapedHtml.source),
|
3933 | reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
|
3934 |
|
3935 | /** Used to match template delimiters. */
|
3936 | var reEscape = /<%-([\s\S]+?)%>/g,
|
3937 | reEvaluate = /<%([\s\S]+?)%>/g,
|
3938 | reInterpolate = /<%=([\s\S]+?)%>/g;
|
3939 |
|
3940 | /** Used to match property names within property paths. */
|
3941 | var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
|
3942 | reIsPlainProp = /^\w*$/,
|
3943 | rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
|
3944 |
|
3945 | /**
|
3946 | * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns)
|
3947 | * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern).
|
3948 | */
|
3949 | var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,
|
3950 | reHasRegExpChars = RegExp(reRegExpChars.source);
|
3951 |
|
3952 | /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */
|
3953 | var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g;
|
3954 |
|
3955 | /** Used to match backslashes in property paths. */
|
3956 | var reEscapeChar = /\\(\\)?/g;
|
3957 |
|
3958 | /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
|
3959 | var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
|
3960 |
|
3961 | /** Used to match `RegExp` flags from their coerced string values. */
|
3962 | var reFlags = /\w*$/;
|
3963 |
|
3964 | /** Used to detect hexadecimal string values. */
|
3965 | var reHasHexPrefix = /^0[xX]/;
|
3966 |
|
3967 | /** Used to detect host constructors (Safari > 5). */
|
3968 | var reIsHostCtor = /^\[object .+?Constructor\]$/;
|
3969 |
|
3970 | /** Used to detect unsigned integer values. */
|
3971 | var reIsUint = /^\d+$/;
|
3972 |
|
3973 | /** Used to match latin-1 supplementary letters (excluding mathematical operators). */
|
3974 | var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
|
3975 |
|
3976 | /** Used to ensure capturing order of template delimiters. */
|
3977 | var reNoMatch = /($^)/;
|
3978 |
|
3979 | /** Used to match unescaped characters in compiled string literals. */
|
3980 | var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
|
3981 |
|
3982 | /** Used to match words to create compound words. */
|
3983 | var reWords = (function() {
|
3984 | var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
|
3985 | lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
|
3986 |
|
3987 | return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
|
3988 | }());
|
3989 |
|
3990 | /** Used to assign default `context` object properties. */
|
3991 | var contextProps = [
|
3992 | 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
|
3993 | 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
|
3994 | 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'isFinite',
|
3995 | 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
|
3996 | 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap'
|
3997 | ];
|
3998 |
|
3999 | /** Used to make template sourceURLs easier to identify. */
|
4000 | var templateCounter = -1;
|
4001 |
|
4002 | /** Used to identify `toStringTag` values of typed arrays. */
|
4003 | var typedArrayTags = {};
|
4004 | typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
|
4005 | typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
|
4006 | typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
|
4007 | typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
|
4008 | typedArrayTags[uint32Tag] = true;
|
4009 | typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
|
4010 | typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
|
4011 | typedArrayTags[dateTag] = typedArrayTags[errorTag] =
|
4012 | typedArrayTags[funcTag] = typedArrayTags[mapTag] =
|
4013 | typedArrayTags[numberTag] = typedArrayTags[objectTag] =
|
4014 | typedArrayTags[regexpTag] = typedArrayTags[setTag] =
|
4015 | typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
|
4016 |
|
4017 | /** Used to identify `toStringTag` values supported by `_.clone`. */
|
4018 | var cloneableTags = {};
|
4019 | cloneableTags[argsTag] = cloneableTags[arrayTag] =
|
4020 | cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
|
4021 | cloneableTags[dateTag] = cloneableTags[float32Tag] =
|
4022 | cloneableTags[float64Tag] = cloneableTags[int8Tag] =
|
4023 | cloneableTags[int16Tag] = cloneableTags[int32Tag] =
|
4024 | cloneableTags[numberTag] = cloneableTags[objectTag] =
|
4025 | cloneableTags[regexpTag] = cloneableTags[stringTag] =
|
4026 | cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
|
4027 | cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
|
4028 | cloneableTags[errorTag] = cloneableTags[funcTag] =
|
4029 | cloneableTags[mapTag] = cloneableTags[setTag] =
|
4030 | cloneableTags[weakMapTag] = false;
|
4031 |
|
4032 | /** Used to map latin-1 supplementary letters to basic latin letters. */
|
4033 | var deburredLetters = {
|
4034 | '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
|
4035 | '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
|
4036 | '\xc7': 'C', '\xe7': 'c',
|
4037 | '\xd0': 'D', '\xf0': 'd',
|
4038 | '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
|
4039 | '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
|
4040 | '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
|
4041 | '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
|
4042 | '\xd1': 'N', '\xf1': 'n',
|
4043 | '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
|
4044 | '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
|
4045 | '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
|
4046 | '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
|
4047 | '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
|
4048 | '\xc6': 'Ae', '\xe6': 'ae',
|
4049 | '\xde': 'Th', '\xfe': 'th',
|
4050 | '\xdf': 'ss'
|
4051 | };
|
4052 |
|
4053 | /** Used to map characters to HTML entities. */
|
4054 | var htmlEscapes = {
|
4055 | '&': '&',
|
4056 | '<': '<',
|
4057 | '>': '>',
|
4058 | '"': '"',
|
4059 | "'": ''',
|
4060 | '`': '`'
|
4061 | };
|
4062 |
|
4063 | /** Used to map HTML entities to characters. */
|
4064 | var htmlUnescapes = {
|
4065 | '&': '&',
|
4066 | '<': '<',
|
4067 | '>': '>',
|
4068 | '"': '"',
|
4069 | ''': "'",
|
4070 | '`': '`'
|
4071 | };
|
4072 |
|
4073 | /** Used to determine if values are of the language type `Object`. */
|
4074 | var objectTypes = {
|
4075 | 'function': true,
|
4076 | 'object': true
|
4077 | };
|
4078 |
|
4079 | /** Used to escape characters for inclusion in compiled regexes. */
|
4080 | var regexpEscapes = {
|
4081 | '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34',
|
4082 | '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39',
|
4083 | 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46',
|
4084 | 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66',
|
4085 | 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78'
|
4086 | };
|
4087 |
|
4088 | /** Used to escape characters for inclusion in compiled string literals. */
|
4089 | var stringEscapes = {
|
4090 | '\\': '\\',
|
4091 | "'": "'",
|
4092 | '\n': 'n',
|
4093 | '\r': 'r',
|
4094 | '\u2028': 'u2028',
|
4095 | '\u2029': 'u2029'
|
4096 | };
|
4097 |
|
4098 | /** Detect free variable `exports`. */
|
4099 | var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
|
4100 |
|
4101 | /** Detect free variable `module`. */
|
4102 | var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
|
4103 |
|
4104 | /** Detect free variable `global` from Node.js. */
|
4105 | var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
|
4106 |
|
4107 | /** Detect free variable `self`. */
|
4108 | var freeSelf = objectTypes[typeof self] && self && self.Object && self;
|
4109 |
|
4110 | /** Detect free variable `window`. */
|
4111 | var freeWindow = objectTypes[typeof window] && window && window.Object && window;
|
4112 |
|
4113 | /** Detect the popular CommonJS extension `module.exports`. */
|
4114 | var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
|
4115 |
|
4116 | /**
|
4117 | * Used as a reference to the global object.
|
4118 | *
|
4119 | * The `this` value is used if it's the global object to avoid Greasemonkey's
|
4120 | * restricted `window` object, otherwise the `window` object is used.
|
4121 | */
|
4122 | var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
|
4123 |
|
4124 | /*--------------------------------------------------------------------------*/
|
4125 |
|
4126 | /**
|
4127 | * The base implementation of `compareAscending` which compares values and
|
4128 | * sorts them in ascending order without guaranteeing a stable sort.
|
4129 | *
|
4130 | * @private
|
4131 | * @param {*} value The value to compare.
|
4132 | * @param {*} other The other value to compare.
|
4133 | * @returns {number} Returns the sort order indicator for `value`.
|
4134 | */
|
4135 | function baseCompareAscending(value, other) {
|
4136 | if (value !== other) {
|
4137 | var valIsNull = value === null,
|
4138 | valIsUndef = value === undefined,
|
4139 | valIsReflexive = value === value;
|
4140 |
|
4141 | var othIsNull = other === null,
|
4142 | othIsUndef = other === undefined,
|
4143 | othIsReflexive = other === other;
|
4144 |
|
4145 | if ((value > other && !othIsNull) || !valIsReflexive ||
|
4146 | (valIsNull && !othIsUndef && othIsReflexive) ||
|
4147 | (valIsUndef && othIsReflexive)) {
|
4148 | return 1;
|
4149 | }
|
4150 | if ((value < other && !valIsNull) || !othIsReflexive ||
|
4151 | (othIsNull && !valIsUndef && valIsReflexive) ||
|
4152 | (othIsUndef && valIsReflexive)) {
|
4153 | return -1;
|
4154 | }
|
4155 | }
|
4156 | return 0;
|
4157 | }
|
4158 |
|
4159 | /**
|
4160 | * The base implementation of `_.findIndex` and `_.findLastIndex` without
|
4161 | * support for callback shorthands and `this` binding.
|
4162 | *
|
4163 | * @private
|
4164 | * @param {Array} array The array to search.
|
4165 | * @param {Function} predicate The function invoked per iteration.
|
4166 | * @param {boolean} [fromRight] Specify iterating from right to left.
|
4167 | * @returns {number} Returns the index of the matched value, else `-1`.
|
4168 | */
|
4169 | function baseFindIndex(array, predicate, fromRight) {
|
4170 | var length = array.length,
|
4171 | index = fromRight ? length : -1;
|
4172 |
|
4173 | while ((fromRight ? index-- : ++index < length)) {
|
4174 | if (predicate(array[index], index, array)) {
|
4175 | return index;
|
4176 | }
|
4177 | }
|
4178 | return -1;
|
4179 | }
|
4180 |
|
4181 | /**
|
4182 | * The base implementation of `_.indexOf` without support for binary searches.
|
4183 | *
|
4184 | * @private
|
4185 | * @param {Array} array The array to search.
|
4186 | * @param {*} value The value to search for.
|
4187 | * @param {number} fromIndex The index to search from.
|
4188 | * @returns {number} Returns the index of the matched value, else `-1`.
|
4189 | */
|
4190 | function baseIndexOf(array, value, fromIndex) {
|
4191 | if (value !== value) {
|
4192 | return indexOfNaN(array, fromIndex);
|
4193 | }
|
4194 | var index = fromIndex - 1,
|
4195 | length = array.length;
|
4196 |
|
4197 | while (++index < length) {
|
4198 | if (array[index] === value) {
|
4199 | return index;
|
4200 | }
|
4201 | }
|
4202 | return -1;
|
4203 | }
|
4204 |
|
4205 | /**
|
4206 | * The base implementation of `_.isFunction` without support for environments
|
4207 | * with incorrect `typeof` results.
|
4208 | *
|
4209 | * @private
|
4210 | * @param {*} value The value to check.
|
4211 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
4212 | */
|
4213 | function baseIsFunction(value) {
|
4214 | // Avoid a Chakra JIT bug in compatibility modes of IE 11.
|
4215 | // See https://github.com/jashkenas/underscore/issues/1621 for more details.
|
4216 | return typeof value == 'function' || false;
|
4217 | }
|
4218 |
|
4219 | /**
|
4220 | * Converts `value` to a string if it's not one. An empty string is returned
|
4221 | * for `null` or `undefined` values.
|
4222 | *
|
4223 | * @private
|
4224 | * @param {*} value The value to process.
|
4225 | * @returns {string} Returns the string.
|
4226 | */
|
4227 | function baseToString(value) {
|
4228 | return value == null ? '' : (value + '');
|
4229 | }
|
4230 |
|
4231 | /**
|
4232 | * Used by `_.trim` and `_.trimLeft` to get the index of the first character
|
4233 | * of `string` that is not found in `chars`.
|
4234 | *
|
4235 | * @private
|
4236 | * @param {string} string The string to inspect.
|
4237 | * @param {string} chars The characters to find.
|
4238 | * @returns {number} Returns the index of the first character not found in `chars`.
|
4239 | */
|
4240 | function charsLeftIndex(string, chars) {
|
4241 | var index = -1,
|
4242 | length = string.length;
|
4243 |
|
4244 | while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
|
4245 | return index;
|
4246 | }
|
4247 |
|
4248 | /**
|
4249 | * Used by `_.trim` and `_.trimRight` to get the index of the last character
|
4250 | * of `string` that is not found in `chars`.
|
4251 | *
|
4252 | * @private
|
4253 | * @param {string} string The string to inspect.
|
4254 | * @param {string} chars The characters to find.
|
4255 | * @returns {number} Returns the index of the last character not found in `chars`.
|
4256 | */
|
4257 | function charsRightIndex(string, chars) {
|
4258 | var index = string.length;
|
4259 |
|
4260 | while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
|
4261 | return index;
|
4262 | }
|
4263 |
|
4264 | /**
|
4265 | * Used by `_.sortBy` to compare transformed elements of a collection and stable
|
4266 | * sort them in ascending order.
|
4267 | *
|
4268 | * @private
|
4269 | * @param {Object} object The object to compare.
|
4270 | * @param {Object} other The other object to compare.
|
4271 | * @returns {number} Returns the sort order indicator for `object`.
|
4272 | */
|
4273 | function compareAscending(object, other) {
|
4274 | return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
|
4275 | }
|
4276 |
|
4277 | /**
|
4278 | * Used by `_.sortByOrder` to compare multiple properties of a value to another
|
4279 | * and stable sort them.
|
4280 | *
|
4281 | * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
|
4282 | * a value is sorted in ascending order if its corresponding order is "asc", and
|
4283 | * descending if "desc".
|
4284 | *
|
4285 | * @private
|
4286 | * @param {Object} object The object to compare.
|
4287 | * @param {Object} other The other object to compare.
|
4288 | * @param {boolean[]} orders The order to sort by for each property.
|
4289 | * @returns {number} Returns the sort order indicator for `object`.
|
4290 | */
|
4291 | function compareMultiple(object, other, orders) {
|
4292 | var index = -1,
|
4293 | objCriteria = object.criteria,
|
4294 | othCriteria = other.criteria,
|
4295 | length = objCriteria.length,
|
4296 | ordersLength = orders.length;
|
4297 |
|
4298 | while (++index < length) {
|
4299 | var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
|
4300 | if (result) {
|
4301 | if (index >= ordersLength) {
|
4302 | return result;
|
4303 | }
|
4304 | var order = orders[index];
|
4305 | return result * ((order === 'asc' || order === true) ? 1 : -1);
|
4306 | }
|
4307 | }
|
4308 | // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
|
4309 | // that causes it, under certain circumstances, to provide the same value for
|
4310 | // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
|
4311 | // for more details.
|
4312 | //
|
4313 | // This also ensures a stable sort in V8 and other engines.
|
4314 | // See https://code.google.com/p/v8/issues/detail?id=90 for more details.
|
4315 | return object.index - other.index;
|
4316 | }
|
4317 |
|
4318 | /**
|
4319 | * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
|
4320 | *
|
4321 | * @private
|
4322 | * @param {string} letter The matched letter to deburr.
|
4323 | * @returns {string} Returns the deburred letter.
|
4324 | */
|
4325 | function deburrLetter(letter) {
|
4326 | return deburredLetters[letter];
|
4327 | }
|
4328 |
|
4329 | /**
|
4330 | * Used by `_.escape` to convert characters to HTML entities.
|
4331 | *
|
4332 | * @private
|
4333 | * @param {string} chr The matched character to escape.
|
4334 | * @returns {string} Returns the escaped character.
|
4335 | */
|
4336 | function escapeHtmlChar(chr) {
|
4337 | return htmlEscapes[chr];
|
4338 | }
|
4339 |
|
4340 | /**
|
4341 | * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes.
|
4342 | *
|
4343 | * @private
|
4344 | * @param {string} chr The matched character to escape.
|
4345 | * @param {string} leadingChar The capture group for a leading character.
|
4346 | * @param {string} whitespaceChar The capture group for a whitespace character.
|
4347 | * @returns {string} Returns the escaped character.
|
4348 | */
|
4349 | function escapeRegExpChar(chr, leadingChar, whitespaceChar) {
|
4350 | if (leadingChar) {
|
4351 | chr = regexpEscapes[chr];
|
4352 | } else if (whitespaceChar) {
|
4353 | chr = stringEscapes[chr];
|
4354 | }
|
4355 | return '\\' + chr;
|
4356 | }
|
4357 |
|
4358 | /**
|
4359 | * Used by `_.template` to escape characters for inclusion in compiled string literals.
|
4360 | *
|
4361 | * @private
|
4362 | * @param {string} chr The matched character to escape.
|
4363 | * @returns {string} Returns the escaped character.
|
4364 | */
|
4365 | function escapeStringChar(chr) {
|
4366 | return '\\' + stringEscapes[chr];
|
4367 | }
|
4368 |
|
4369 | /**
|
4370 | * Gets the index at which the first occurrence of `NaN` is found in `array`.
|
4371 | *
|
4372 | * @private
|
4373 | * @param {Array} array The array to search.
|
4374 | * @param {number} fromIndex The index to search from.
|
4375 | * @param {boolean} [fromRight] Specify iterating from right to left.
|
4376 | * @returns {number} Returns the index of the matched `NaN`, else `-1`.
|
4377 | */
|
4378 | function indexOfNaN(array, fromIndex, fromRight) {
|
4379 | var length = array.length,
|
4380 | index = fromIndex + (fromRight ? 0 : -1);
|
4381 |
|
4382 | while ((fromRight ? index-- : ++index < length)) {
|
4383 | var other = array[index];
|
4384 | if (other !== other) {
|
4385 | return index;
|
4386 | }
|
4387 | }
|
4388 | return -1;
|
4389 | }
|
4390 |
|
4391 | /**
|
4392 | * Checks if `value` is object-like.
|
4393 | *
|
4394 | * @private
|
4395 | * @param {*} value The value to check.
|
4396 | * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
|
4397 | */
|
4398 | function isObjectLike(value) {
|
4399 | return !!value && typeof value == 'object';
|
4400 | }
|
4401 |
|
4402 | /**
|
4403 | * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
|
4404 | * character code is whitespace.
|
4405 | *
|
4406 | * @private
|
4407 | * @param {number} charCode The character code to inspect.
|
4408 | * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
|
4409 | */
|
4410 | function isSpace(charCode) {
|
4411 | return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
|
4412 | (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
|
4413 | }
|
4414 |
|
4415 | /**
|
4416 | * Replaces all `placeholder` elements in `array` with an internal placeholder
|
4417 | * and returns an array of their indexes.
|
4418 | *
|
4419 | * @private
|
4420 | * @param {Array} array The array to modify.
|
4421 | * @param {*} placeholder The placeholder to replace.
|
4422 | * @returns {Array} Returns the new array of placeholder indexes.
|
4423 | */
|
4424 | function replaceHolders(array, placeholder) {
|
4425 | var index = -1,
|
4426 | length = array.length,
|
4427 | resIndex = -1,
|
4428 | result = [];
|
4429 |
|
4430 | while (++index < length) {
|
4431 | if (array[index] === placeholder) {
|
4432 | array[index] = PLACEHOLDER;
|
4433 | result[++resIndex] = index;
|
4434 | }
|
4435 | }
|
4436 | return result;
|
4437 | }
|
4438 |
|
4439 | /**
|
4440 | * An implementation of `_.uniq` optimized for sorted arrays without support
|
4441 | * for callback shorthands and `this` binding.
|
4442 | *
|
4443 | * @private
|
4444 | * @param {Array} array The array to inspect.
|
4445 | * @param {Function} [iteratee] The function invoked per iteration.
|
4446 | * @returns {Array} Returns the new duplicate-value-free array.
|
4447 | */
|
4448 | function sortedUniq(array, iteratee) {
|
4449 | var seen,
|
4450 | index = -1,
|
4451 | length = array.length,
|
4452 | resIndex = -1,
|
4453 | result = [];
|
4454 |
|
4455 | while (++index < length) {
|
4456 | var value = array[index],
|
4457 | computed = iteratee ? iteratee(value, index, array) : value;
|
4458 |
|
4459 | if (!index || seen !== computed) {
|
4460 | seen = computed;
|
4461 | result[++resIndex] = value;
|
4462 | }
|
4463 | }
|
4464 | return result;
|
4465 | }
|
4466 |
|
4467 | /**
|
4468 | * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
|
4469 | * character of `string`.
|
4470 | *
|
4471 | * @private
|
4472 | * @param {string} string The string to inspect.
|
4473 | * @returns {number} Returns the index of the first non-whitespace character.
|
4474 | */
|
4475 | function trimmedLeftIndex(string) {
|
4476 | var index = -1,
|
4477 | length = string.length;
|
4478 |
|
4479 | while (++index < length && isSpace(string.charCodeAt(index))) {}
|
4480 | return index;
|
4481 | }
|
4482 |
|
4483 | /**
|
4484 | * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
|
4485 | * character of `string`.
|
4486 | *
|
4487 | * @private
|
4488 | * @param {string} string The string to inspect.
|
4489 | * @returns {number} Returns the index of the last non-whitespace character.
|
4490 | */
|
4491 | function trimmedRightIndex(string) {
|
4492 | var index = string.length;
|
4493 |
|
4494 | while (index-- && isSpace(string.charCodeAt(index))) {}
|
4495 | return index;
|
4496 | }
|
4497 |
|
4498 | /**
|
4499 | * Used by `_.unescape` to convert HTML entities to characters.
|
4500 | *
|
4501 | * @private
|
4502 | * @param {string} chr The matched character to unescape.
|
4503 | * @returns {string} Returns the unescaped character.
|
4504 | */
|
4505 | function unescapeHtmlChar(chr) {
|
4506 | return htmlUnescapes[chr];
|
4507 | }
|
4508 |
|
4509 | /*--------------------------------------------------------------------------*/
|
4510 |
|
4511 | /**
|
4512 | * Create a new pristine `lodash` function using the given `context` object.
|
4513 | *
|
4514 | * @static
|
4515 | * @memberOf _
|
4516 | * @category Utility
|
4517 | * @param {Object} [context=root] The context object.
|
4518 | * @returns {Function} Returns a new `lodash` function.
|
4519 | * @example
|
4520 | *
|
4521 | * _.mixin({ 'foo': _.constant('foo') });
|
4522 | *
|
4523 | * var lodash = _.runInContext();
|
4524 | * lodash.mixin({ 'bar': lodash.constant('bar') });
|
4525 | *
|
4526 | * _.isFunction(_.foo);
|
4527 | * // => true
|
4528 | * _.isFunction(_.bar);
|
4529 | * // => false
|
4530 | *
|
4531 | * lodash.isFunction(lodash.foo);
|
4532 | * // => false
|
4533 | * lodash.isFunction(lodash.bar);
|
4534 | * // => true
|
4535 | *
|
4536 | * // using `context` to mock `Date#getTime` use in `_.now`
|
4537 | * var mock = _.runInContext({
|
4538 | * 'Date': function() {
|
4539 | * return { 'getTime': getTimeMock };
|
4540 | * }
|
4541 | * });
|
4542 | *
|
4543 | * // or creating a suped-up `defer` in Node.js
|
4544 | * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
|
4545 | */
|
4546 | function runInContext(context) {
|
4547 | // Avoid issues with some ES3 environments that attempt to use values, named
|
4548 | // after built-in constructors like `Object`, for the creation of literals.
|
4549 | // ES5 clears this up by stating that literals must use built-in constructors.
|
4550 | // See https://es5.github.io/#x11.1.5 for more details.
|
4551 | context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
|
4552 |
|
4553 | /** Native constructor references. */
|
4554 | var Array = context.Array,
|
4555 | Date = context.Date,
|
4556 | Error = context.Error,
|
4557 | Function = context.Function,
|
4558 | Math = context.Math,
|
4559 | Number = context.Number,
|
4560 | Object = context.Object,
|
4561 | RegExp = context.RegExp,
|
4562 | String = context.String,
|
4563 | TypeError = context.TypeError;
|
4564 |
|
4565 | /** Used for native method references. */
|
4566 | var arrayProto = Array.prototype,
|
4567 | objectProto = Object.prototype,
|
4568 | stringProto = String.prototype;
|
4569 |
|
4570 | /** Used to resolve the decompiled source of functions. */
|
4571 | var fnToString = Function.prototype.toString;
|
4572 |
|
4573 | /** Used to check objects for own properties. */
|
4574 | var hasOwnProperty = objectProto.hasOwnProperty;
|
4575 |
|
4576 | /** Used to generate unique IDs. */
|
4577 | var idCounter = 0;
|
4578 |
|
4579 | /**
|
4580 | * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
|
4581 | * of values.
|
4582 | */
|
4583 | var objToString = objectProto.toString;
|
4584 |
|
4585 | /** Used to restore the original `_` reference in `_.noConflict`. */
|
4586 | var oldDash = root._;
|
4587 |
|
4588 | /** Used to detect if a method is native. */
|
4589 | var reIsNative = RegExp('^' +
|
4590 | fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
|
4591 | .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
|
4592 | );
|
4593 |
|
4594 | /** Native method references. */
|
4595 | var ArrayBuffer = context.ArrayBuffer,
|
4596 | clearTimeout = context.clearTimeout,
|
4597 | parseFloat = context.parseFloat,
|
4598 | pow = Math.pow,
|
4599 | propertyIsEnumerable = objectProto.propertyIsEnumerable,
|
4600 | Set = getNative(context, 'Set'),
|
4601 | setTimeout = context.setTimeout,
|
4602 | splice = arrayProto.splice,
|
4603 | Uint8Array = context.Uint8Array,
|
4604 | WeakMap = getNative(context, 'WeakMap');
|
4605 |
|
4606 | /* Native method references for those with the same name as other `lodash` methods. */
|
4607 | var nativeCeil = Math.ceil,
|
4608 | nativeCreate = getNative(Object, 'create'),
|
4609 | nativeFloor = Math.floor,
|
4610 | nativeIsArray = getNative(Array, 'isArray'),
|
4611 | nativeIsFinite = context.isFinite,
|
4612 | nativeKeys = getNative(Object, 'keys'),
|
4613 | nativeMax = Math.max,
|
4614 | nativeMin = Math.min,
|
4615 | nativeNow = getNative(Date, 'now'),
|
4616 | nativeParseInt = context.parseInt,
|
4617 | nativeRandom = Math.random;
|
4618 |
|
4619 | /** Used as references for `-Infinity` and `Infinity`. */
|
4620 | var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
|
4621 | POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
|
4622 |
|
4623 | /** Used as references for the maximum length and index of an array. */
|
4624 | var MAX_ARRAY_LENGTH = 4294967295,
|
4625 | MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
|
4626 | HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
|
4627 |
|
4628 | /**
|
4629 | * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
|
4630 | * of an array-like value.
|
4631 | */
|
4632 | var MAX_SAFE_INTEGER = 9007199254740991;
|
4633 |
|
4634 | /** Used to store function metadata. */
|
4635 | var metaMap = WeakMap && new WeakMap;
|
4636 |
|
4637 | /** Used to lookup unminified function names. */
|
4638 | var realNames = {};
|
4639 |
|
4640 | /*------------------------------------------------------------------------*/
|
4641 |
|
4642 | /**
|
4643 | * Creates a `lodash` object which wraps `value` to enable implicit chaining.
|
4644 | * Methods that operate on and return arrays, collections, and functions can
|
4645 | * be chained together. Methods that retrieve a single value or may return a
|
4646 | * primitive value will automatically end the chain returning the unwrapped
|
4647 | * value. Explicit chaining may be enabled using `_.chain`. The execution of
|
4648 | * chained methods is lazy, that is, execution is deferred until `_#value`
|
4649 | * is implicitly or explicitly called.
|
4650 | *
|
4651 | * Lazy evaluation allows several methods to support shortcut fusion. Shortcut
|
4652 | * fusion is an optimization strategy which merge iteratee calls; this can help
|
4653 | * to avoid the creation of intermediate data structures and greatly reduce the
|
4654 | * number of iteratee executions.
|
4655 | *
|
4656 | * Chaining is supported in custom builds as long as the `_#value` method is
|
4657 | * directly or indirectly included in the build.
|
4658 | *
|
4659 | * In addition to lodash methods, wrappers have `Array` and `String` methods.
|
4660 | *
|
4661 | * The wrapper `Array` methods are:
|
4662 | * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
|
4663 | * `splice`, and `unshift`
|
4664 | *
|
4665 | * The wrapper `String` methods are:
|
4666 | * `replace` and `split`
|
4667 | *
|
4668 | * The wrapper methods that support shortcut fusion are:
|
4669 | * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
|
4670 | * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
|
4671 | * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
|
4672 | * and `where`
|
4673 | *
|
4674 | * The chainable wrapper methods are:
|
4675 | * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
|
4676 | * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
|
4677 | * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`,
|
4678 | * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`,
|
4679 | * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`,
|
4680 | * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
|
4681 | * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
|
4682 | * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`,
|
4683 | * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`,
|
4684 | * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
|
4685 | * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
|
4686 | * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`,
|
4687 | * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`,
|
4688 | * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`,
|
4689 | * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
|
4690 | * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`,
|
4691 | * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
|
4692 | *
|
4693 | * The wrapper methods that are **not** chainable by default are:
|
4694 | * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`,
|
4695 | * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
|
4696 | * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`,
|
4697 | * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`,
|
4698 | * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
|
4699 | * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`,
|
4700 | * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`,
|
4701 | * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`,
|
4702 | * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`,
|
4703 | * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`,
|
4704 | * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`,
|
4705 | * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`,
|
4706 | * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
|
4707 | * `unescape`, `uniqueId`, `value`, and `words`
|
4708 | *
|
4709 | * The wrapper method `sample` will return a wrapped value when `n` is provided,
|
4710 | * otherwise an unwrapped value is returned.
|
4711 | *
|
4712 | * @name _
|
4713 | * @constructor
|
4714 | * @category Chain
|
4715 | * @param {*} value The value to wrap in a `lodash` instance.
|
4716 | * @returns {Object} Returns the new `lodash` wrapper instance.
|
4717 | * @example
|
4718 | *
|
4719 | * var wrapped = _([1, 2, 3]);
|
4720 | *
|
4721 | * // returns an unwrapped value
|
4722 | * wrapped.reduce(function(total, n) {
|
4723 | * return total + n;
|
4724 | * });
|
4725 | * // => 6
|
4726 | *
|
4727 | * // returns a wrapped value
|
4728 | * var squares = wrapped.map(function(n) {
|
4729 | * return n * n;
|
4730 | * });
|
4731 | *
|
4732 | * _.isArray(squares);
|
4733 | * // => false
|
4734 | *
|
4735 | * _.isArray(squares.value());
|
4736 | * // => true
|
4737 | */
|
4738 | function lodash(value) {
|
4739 | if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
|
4740 | if (value instanceof LodashWrapper) {
|
4741 | return value;
|
4742 | }
|
4743 | if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
|
4744 | return wrapperClone(value);
|
4745 | }
|
4746 | }
|
4747 | return new LodashWrapper(value);
|
4748 | }
|
4749 |
|
4750 | /**
|
4751 | * The function whose prototype all chaining wrappers inherit from.
|
4752 | *
|
4753 | * @private
|
4754 | */
|
4755 | function baseLodash() {
|
4756 | // No operation performed.
|
4757 | }
|
4758 |
|
4759 | /**
|
4760 | * The base constructor for creating `lodash` wrapper objects.
|
4761 | *
|
4762 | * @private
|
4763 | * @param {*} value The value to wrap.
|
4764 | * @param {boolean} [chainAll] Enable chaining for all wrapper methods.
|
4765 | * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
|
4766 | */
|
4767 | function LodashWrapper(value, chainAll, actions) {
|
4768 | this.__wrapped__ = value;
|
4769 | this.__actions__ = actions || [];
|
4770 | this.__chain__ = !!chainAll;
|
4771 | }
|
4772 |
|
4773 | /**
|
4774 | * An object environment feature flags.
|
4775 | *
|
4776 | * @static
|
4777 | * @memberOf _
|
4778 | * @type Object
|
4779 | */
|
4780 | var support = lodash.support = {};
|
4781 |
|
4782 | /**
|
4783 | * By default, the template delimiters used by lodash are like those in
|
4784 | * embedded Ruby (ERB). Change the following template settings to use
|
4785 | * alternative delimiters.
|
4786 | *
|
4787 | * @static
|
4788 | * @memberOf _
|
4789 | * @type Object
|
4790 | */
|
4791 | lodash.templateSettings = {
|
4792 |
|
4793 | /**
|
4794 | * Used to detect `data` property values to be HTML-escaped.
|
4795 | *
|
4796 | * @memberOf _.templateSettings
|
4797 | * @type RegExp
|
4798 | */
|
4799 | 'escape': reEscape,
|
4800 |
|
4801 | /**
|
4802 | * Used to detect code to be evaluated.
|
4803 | *
|
4804 | * @memberOf _.templateSettings
|
4805 | * @type RegExp
|
4806 | */
|
4807 | 'evaluate': reEvaluate,
|
4808 |
|
4809 | /**
|
4810 | * Used to detect `data` property values to inject.
|
4811 | *
|
4812 | * @memberOf _.templateSettings
|
4813 | * @type RegExp
|
4814 | */
|
4815 | 'interpolate': reInterpolate,
|
4816 |
|
4817 | /**
|
4818 | * Used to reference the data object in the template text.
|
4819 | *
|
4820 | * @memberOf _.templateSettings
|
4821 | * @type string
|
4822 | */
|
4823 | 'variable': '',
|
4824 |
|
4825 | /**
|
4826 | * Used to import variables into the compiled template.
|
4827 | *
|
4828 | * @memberOf _.templateSettings
|
4829 | * @type Object
|
4830 | */
|
4831 | 'imports': {
|
4832 |
|
4833 | /**
|
4834 | * A reference to the `lodash` function.
|
4835 | *
|
4836 | * @memberOf _.templateSettings.imports
|
4837 | * @type Function
|
4838 | */
|
4839 | '_': lodash
|
4840 | }
|
4841 | };
|
4842 |
|
4843 | /*------------------------------------------------------------------------*/
|
4844 |
|
4845 | /**
|
4846 | * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
|
4847 | *
|
4848 | * @private
|
4849 | * @param {*} value The value to wrap.
|
4850 | */
|
4851 | function LazyWrapper(value) {
|
4852 | this.__wrapped__ = value;
|
4853 | this.__actions__ = [];
|
4854 | this.__dir__ = 1;
|
4855 | this.__filtered__ = false;
|
4856 | this.__iteratees__ = [];
|
4857 | this.__takeCount__ = POSITIVE_INFINITY;
|
4858 | this.__views__ = [];
|
4859 | }
|
4860 |
|
4861 | /**
|
4862 | * Creates a clone of the lazy wrapper object.
|
4863 | *
|
4864 | * @private
|
4865 | * @name clone
|
4866 | * @memberOf LazyWrapper
|
4867 | * @returns {Object} Returns the cloned `LazyWrapper` object.
|
4868 | */
|
4869 | function lazyClone() {
|
4870 | var result = new LazyWrapper(this.__wrapped__);
|
4871 | result.__actions__ = arrayCopy(this.__actions__);
|
4872 | result.__dir__ = this.__dir__;
|
4873 | result.__filtered__ = this.__filtered__;
|
4874 | result.__iteratees__ = arrayCopy(this.__iteratees__);
|
4875 | result.__takeCount__ = this.__takeCount__;
|
4876 | result.__views__ = arrayCopy(this.__views__);
|
4877 | return result;
|
4878 | }
|
4879 |
|
4880 | /**
|
4881 | * Reverses the direction of lazy iteration.
|
4882 | *
|
4883 | * @private
|
4884 | * @name reverse
|
4885 | * @memberOf LazyWrapper
|
4886 | * @returns {Object} Returns the new reversed `LazyWrapper` object.
|
4887 | */
|
4888 | function lazyReverse() {
|
4889 | if (this.__filtered__) {
|
4890 | var result = new LazyWrapper(this);
|
4891 | result.__dir__ = -1;
|
4892 | result.__filtered__ = true;
|
4893 | } else {
|
4894 | result = this.clone();
|
4895 | result.__dir__ *= -1;
|
4896 | }
|
4897 | return result;
|
4898 | }
|
4899 |
|
4900 | /**
|
4901 | * Extracts the unwrapped value from its lazy wrapper.
|
4902 | *
|
4903 | * @private
|
4904 | * @name value
|
4905 | * @memberOf LazyWrapper
|
4906 | * @returns {*} Returns the unwrapped value.
|
4907 | */
|
4908 | function lazyValue() {
|
4909 | var array = this.__wrapped__.value(),
|
4910 | dir = this.__dir__,
|
4911 | isArr = isArray(array),
|
4912 | isRight = dir < 0,
|
4913 | arrLength = isArr ? array.length : 0,
|
4914 | view = getView(0, arrLength, this.__views__),
|
4915 | start = view.start,
|
4916 | end = view.end,
|
4917 | length = end - start,
|
4918 | index = isRight ? end : (start - 1),
|
4919 | iteratees = this.__iteratees__,
|
4920 | iterLength = iteratees.length,
|
4921 | resIndex = 0,
|
4922 | takeCount = nativeMin(length, this.__takeCount__);
|
4923 |
|
4924 | if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) {
|
4925 | return baseWrapperValue((isRight && isArr) ? array.reverse() : array, this.__actions__);
|
4926 | }
|
4927 | var result = [];
|
4928 |
|
4929 | outer:
|
4930 | while (length-- && resIndex < takeCount) {
|
4931 | index += dir;
|
4932 |
|
4933 | var iterIndex = -1,
|
4934 | value = array[index];
|
4935 |
|
4936 | while (++iterIndex < iterLength) {
|
4937 | var data = iteratees[iterIndex],
|
4938 | iteratee = data.iteratee,
|
4939 | type = data.type,
|
4940 | computed = iteratee(value);
|
4941 |
|
4942 | if (type == LAZY_MAP_FLAG) {
|
4943 | value = computed;
|
4944 | } else if (!computed) {
|
4945 | if (type == LAZY_FILTER_FLAG) {
|
4946 | continue outer;
|
4947 | } else {
|
4948 | break outer;
|
4949 | }
|
4950 | }
|
4951 | }
|
4952 | result[resIndex++] = value;
|
4953 | }
|
4954 | return result;
|
4955 | }
|
4956 |
|
4957 | /*------------------------------------------------------------------------*/
|
4958 |
|
4959 | /**
|
4960 | * Creates a cache object to store key/value pairs.
|
4961 | *
|
4962 | * @private
|
4963 | * @static
|
4964 | * @name Cache
|
4965 | * @memberOf _.memoize
|
4966 | */
|
4967 | function MapCache() {
|
4968 | this.__data__ = {};
|
4969 | }
|
4970 |
|
4971 | /**
|
4972 | * Removes `key` and its value from the cache.
|
4973 | *
|
4974 | * @private
|
4975 | * @name delete
|
4976 | * @memberOf _.memoize.Cache
|
4977 | * @param {string} key The key of the value to remove.
|
4978 | * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
|
4979 | */
|
4980 | function mapDelete(key) {
|
4981 | return this.has(key) && delete this.__data__[key];
|
4982 | }
|
4983 |
|
4984 | /**
|
4985 | * Gets the cached value for `key`.
|
4986 | *
|
4987 | * @private
|
4988 | * @name get
|
4989 | * @memberOf _.memoize.Cache
|
4990 | * @param {string} key The key of the value to get.
|
4991 | * @returns {*} Returns the cached value.
|
4992 | */
|
4993 | function mapGet(key) {
|
4994 | return key == '__proto__' ? undefined : this.__data__[key];
|
4995 | }
|
4996 |
|
4997 | /**
|
4998 | * Checks if a cached value for `key` exists.
|
4999 | *
|
5000 | * @private
|
5001 | * @name has
|
5002 | * @memberOf _.memoize.Cache
|
5003 | * @param {string} key The key of the entry to check.
|
5004 | * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
|
5005 | */
|
5006 | function mapHas(key) {
|
5007 | return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
|
5008 | }
|
5009 |
|
5010 | /**
|
5011 | * Sets `value` to `key` of the cache.
|
5012 | *
|
5013 | * @private
|
5014 | * @name set
|
5015 | * @memberOf _.memoize.Cache
|
5016 | * @param {string} key The key of the value to cache.
|
5017 | * @param {*} value The value to cache.
|
5018 | * @returns {Object} Returns the cache object.
|
5019 | */
|
5020 | function mapSet(key, value) {
|
5021 | if (key != '__proto__') {
|
5022 | this.__data__[key] = value;
|
5023 | }
|
5024 | return this;
|
5025 | }
|
5026 |
|
5027 | /*------------------------------------------------------------------------*/
|
5028 |
|
5029 | /**
|
5030 | *
|
5031 | * Creates a cache object to store unique values.
|
5032 | *
|
5033 | * @private
|
5034 | * @param {Array} [values] The values to cache.
|
5035 | */
|
5036 | function SetCache(values) {
|
5037 | var length = values ? values.length : 0;
|
5038 |
|
5039 | this.data = { 'hash': nativeCreate(null), 'set': new Set };
|
5040 | while (length--) {
|
5041 | this.push(values[length]);
|
5042 | }
|
5043 | }
|
5044 |
|
5045 | /**
|
5046 | * Checks if `value` is in `cache` mimicking the return signature of
|
5047 | * `_.indexOf` by returning `0` if the value is found, else `-1`.
|
5048 | *
|
5049 | * @private
|
5050 | * @param {Object} cache The cache to search.
|
5051 | * @param {*} value The value to search for.
|
5052 | * @returns {number} Returns `0` if `value` is found, else `-1`.
|
5053 | */
|
5054 | function cacheIndexOf(cache, value) {
|
5055 | var data = cache.data,
|
5056 | result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];
|
5057 |
|
5058 | return result ? 0 : -1;
|
5059 | }
|
5060 |
|
5061 | /**
|
5062 | * Adds `value` to the cache.
|
5063 | *
|
5064 | * @private
|
5065 | * @name push
|
5066 | * @memberOf SetCache
|
5067 | * @param {*} value The value to cache.
|
5068 | */
|
5069 | function cachePush(value) {
|
5070 | var data = this.data;
|
5071 | if (typeof value == 'string' || isObject(value)) {
|
5072 | data.set.add(value);
|
5073 | } else {
|
5074 | data.hash[value] = true;
|
5075 | }
|
5076 | }
|
5077 |
|
5078 | /*------------------------------------------------------------------------*/
|
5079 |
|
5080 | /**
|
5081 | * Creates a new array joining `array` with `other`.
|
5082 | *
|
5083 | * @private
|
5084 | * @param {Array} array The array to join.
|
5085 | * @param {Array} other The other array to join.
|
5086 | * @returns {Array} Returns the new concatenated array.
|
5087 | */
|
5088 | function arrayConcat(array, other) {
|
5089 | var index = -1,
|
5090 | length = array.length,
|
5091 | othIndex = -1,
|
5092 | othLength = other.length,
|
5093 | result = Array(length + othLength);
|
5094 |
|
5095 | while (++index < length) {
|
5096 | result[index] = array[index];
|
5097 | }
|
5098 | while (++othIndex < othLength) {
|
5099 | result[index++] = other[othIndex];
|
5100 | }
|
5101 | return result;
|
5102 | }
|
5103 |
|
5104 | /**
|
5105 | * Copies the values of `source` to `array`.
|
5106 | *
|
5107 | * @private
|
5108 | * @param {Array} source The array to copy values from.
|
5109 | * @param {Array} [array=[]] The array to copy values to.
|
5110 | * @returns {Array} Returns `array`.
|
5111 | */
|
5112 | function arrayCopy(source, array) {
|
5113 | var index = -1,
|
5114 | length = source.length;
|
5115 |
|
5116 | array || (array = Array(length));
|
5117 | while (++index < length) {
|
5118 | array[index] = source[index];
|
5119 | }
|
5120 | return array;
|
5121 | }
|
5122 |
|
5123 | /**
|
5124 | * A specialized version of `_.forEach` for arrays without support for callback
|
5125 | * shorthands and `this` binding.
|
5126 | *
|
5127 | * @private
|
5128 | * @param {Array} array The array to iterate over.
|
5129 | * @param {Function} iteratee The function invoked per iteration.
|
5130 | * @returns {Array} Returns `array`.
|
5131 | */
|
5132 | function arrayEach(array, iteratee) {
|
5133 | var index = -1,
|
5134 | length = array.length;
|
5135 |
|
5136 | while (++index < length) {
|
5137 | if (iteratee(array[index], index, array) === false) {
|
5138 | break;
|
5139 | }
|
5140 | }
|
5141 | return array;
|
5142 | }
|
5143 |
|
5144 | /**
|
5145 | * A specialized version of `_.forEachRight` for arrays without support for
|
5146 | * callback shorthands and `this` binding.
|
5147 | *
|
5148 | * @private
|
5149 | * @param {Array} array The array to iterate over.
|
5150 | * @param {Function} iteratee The function invoked per iteration.
|
5151 | * @returns {Array} Returns `array`.
|
5152 | */
|
5153 | function arrayEachRight(array, iteratee) {
|
5154 | var length = array.length;
|
5155 |
|
5156 | while (length--) {
|
5157 | if (iteratee(array[length], length, array) === false) {
|
5158 | break;
|
5159 | }
|
5160 | }
|
5161 | return array;
|
5162 | }
|
5163 |
|
5164 | /**
|
5165 | * A specialized version of `_.every` for arrays without support for callback
|
5166 | * shorthands and `this` binding.
|
5167 | *
|
5168 | * @private
|
5169 | * @param {Array} array The array to iterate over.
|
5170 | * @param {Function} predicate The function invoked per iteration.
|
5171 | * @returns {boolean} Returns `true` if all elements pass the predicate check,
|
5172 | * else `false`.
|
5173 | */
|
5174 | function arrayEvery(array, predicate) {
|
5175 | var index = -1,
|
5176 | length = array.length;
|
5177 |
|
5178 | while (++index < length) {
|
5179 | if (!predicate(array[index], index, array)) {
|
5180 | return false;
|
5181 | }
|
5182 | }
|
5183 | return true;
|
5184 | }
|
5185 |
|
5186 | /**
|
5187 | * A specialized version of `baseExtremum` for arrays which invokes `iteratee`
|
5188 | * with one argument: (value).
|
5189 | *
|
5190 | * @private
|
5191 | * @param {Array} array The array to iterate over.
|
5192 | * @param {Function} iteratee The function invoked per iteration.
|
5193 | * @param {Function} comparator The function used to compare values.
|
5194 | * @param {*} exValue The initial extremum value.
|
5195 | * @returns {*} Returns the extremum value.
|
5196 | */
|
5197 | function arrayExtremum(array, iteratee, comparator, exValue) {
|
5198 | var index = -1,
|
5199 | length = array.length,
|
5200 | computed = exValue,
|
5201 | result = computed;
|
5202 |
|
5203 | while (++index < length) {
|
5204 | var value = array[index],
|
5205 | current = +iteratee(value);
|
5206 |
|
5207 | if (comparator(current, computed)) {
|
5208 | computed = current;
|
5209 | result = value;
|
5210 | }
|
5211 | }
|
5212 | return result;
|
5213 | }
|
5214 |
|
5215 | /**
|
5216 | * A specialized version of `_.filter` for arrays without support for callback
|
5217 | * shorthands and `this` binding.
|
5218 | *
|
5219 | * @private
|
5220 | * @param {Array} array The array to iterate over.
|
5221 | * @param {Function} predicate The function invoked per iteration.
|
5222 | * @returns {Array} Returns the new filtered array.
|
5223 | */
|
5224 | function arrayFilter(array, predicate) {
|
5225 | var index = -1,
|
5226 | length = array.length,
|
5227 | resIndex = -1,
|
5228 | result = [];
|
5229 |
|
5230 | while (++index < length) {
|
5231 | var value = array[index];
|
5232 | if (predicate(value, index, array)) {
|
5233 | result[++resIndex] = value;
|
5234 | }
|
5235 | }
|
5236 | return result;
|
5237 | }
|
5238 |
|
5239 | /**
|
5240 | * A specialized version of `_.map` for arrays without support for callback
|
5241 | * shorthands and `this` binding.
|
5242 | *
|
5243 | * @private
|
5244 | * @param {Array} array The array to iterate over.
|
5245 | * @param {Function} iteratee The function invoked per iteration.
|
5246 | * @returns {Array} Returns the new mapped array.
|
5247 | */
|
5248 | function arrayMap(array, iteratee) {
|
5249 | var index = -1,
|
5250 | length = array.length,
|
5251 | result = Array(length);
|
5252 |
|
5253 | while (++index < length) {
|
5254 | result[index] = iteratee(array[index], index, array);
|
5255 | }
|
5256 | return result;
|
5257 | }
|
5258 |
|
5259 | /**
|
5260 | * Appends the elements of `values` to `array`.
|
5261 | *
|
5262 | * @private
|
5263 | * @param {Array} array The array to modify.
|
5264 | * @param {Array} values The values to append.
|
5265 | * @returns {Array} Returns `array`.
|
5266 | */
|
5267 | function arrayPush(array, values) {
|
5268 | var index = -1,
|
5269 | length = values.length,
|
5270 | offset = array.length;
|
5271 |
|
5272 | while (++index < length) {
|
5273 | array[offset + index] = values[index];
|
5274 | }
|
5275 | return array;
|
5276 | }
|
5277 |
|
5278 | /**
|
5279 | * A specialized version of `_.reduce` for arrays without support for callback
|
5280 | * shorthands and `this` binding.
|
5281 | *
|
5282 | * @private
|
5283 | * @param {Array} array The array to iterate over.
|
5284 | * @param {Function} iteratee The function invoked per iteration.
|
5285 | * @param {*} [accumulator] The initial value.
|
5286 | * @param {boolean} [initFromArray] Specify using the first element of `array`
|
5287 | * as the initial value.
|
5288 | * @returns {*} Returns the accumulated value.
|
5289 | */
|
5290 | function arrayReduce(array, iteratee, accumulator, initFromArray) {
|
5291 | var index = -1,
|
5292 | length = array.length;
|
5293 |
|
5294 | if (initFromArray && length) {
|
5295 | accumulator = array[++index];
|
5296 | }
|
5297 | while (++index < length) {
|
5298 | accumulator = iteratee(accumulator, array[index], index, array);
|
5299 | }
|
5300 | return accumulator;
|
5301 | }
|
5302 |
|
5303 | /**
|
5304 | * A specialized version of `_.reduceRight` for arrays without support for
|
5305 | * callback shorthands and `this` binding.
|
5306 | *
|
5307 | * @private
|
5308 | * @param {Array} array The array to iterate over.
|
5309 | * @param {Function} iteratee The function invoked per iteration.
|
5310 | * @param {*} [accumulator] The initial value.
|
5311 | * @param {boolean} [initFromArray] Specify using the last element of `array`
|
5312 | * as the initial value.
|
5313 | * @returns {*} Returns the accumulated value.
|
5314 | */
|
5315 | function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
|
5316 | var length = array.length;
|
5317 | if (initFromArray && length) {
|
5318 | accumulator = array[--length];
|
5319 | }
|
5320 | while (length--) {
|
5321 | accumulator = iteratee(accumulator, array[length], length, array);
|
5322 | }
|
5323 | return accumulator;
|
5324 | }
|
5325 |
|
5326 | /**
|
5327 | * A specialized version of `_.some` for arrays without support for callback
|
5328 | * shorthands and `this` binding.
|
5329 | *
|
5330 | * @private
|
5331 | * @param {Array} array The array to iterate over.
|
5332 | * @param {Function} predicate The function invoked per iteration.
|
5333 | * @returns {boolean} Returns `true` if any element passes the predicate check,
|
5334 | * else `false`.
|
5335 | */
|
5336 | function arraySome(array, predicate) {
|
5337 | var index = -1,
|
5338 | length = array.length;
|
5339 |
|
5340 | while (++index < length) {
|
5341 | if (predicate(array[index], index, array)) {
|
5342 | return true;
|
5343 | }
|
5344 | }
|
5345 | return false;
|
5346 | }
|
5347 |
|
5348 | /**
|
5349 | * A specialized version of `_.sum` for arrays without support for callback
|
5350 | * shorthands and `this` binding..
|
5351 | *
|
5352 | * @private
|
5353 | * @param {Array} array The array to iterate over.
|
5354 | * @param {Function} iteratee The function invoked per iteration.
|
5355 | * @returns {number} Returns the sum.
|
5356 | */
|
5357 | function arraySum(array, iteratee) {
|
5358 | var length = array.length,
|
5359 | result = 0;
|
5360 |
|
5361 | while (length--) {
|
5362 | result += +iteratee(array[length]) || 0;
|
5363 | }
|
5364 | return result;
|
5365 | }
|
5366 |
|
5367 | /**
|
5368 | * Used by `_.defaults` to customize its `_.assign` use.
|
5369 | *
|
5370 | * @private
|
5371 | * @param {*} objectValue The destination object property value.
|
5372 | * @param {*} sourceValue The source object property value.
|
5373 | * @returns {*} Returns the value to assign to the destination object.
|
5374 | */
|
5375 | function assignDefaults(objectValue, sourceValue) {
|
5376 | return objectValue === undefined ? sourceValue : objectValue;
|
5377 | }
|
5378 |
|
5379 | /**
|
5380 | * Used by `_.template` to customize its `_.assign` use.
|
5381 | *
|
5382 | * **Note:** This function is like `assignDefaults` except that it ignores
|
5383 | * inherited property values when checking if a property is `undefined`.
|
5384 | *
|
5385 | * @private
|
5386 | * @param {*} objectValue The destination object property value.
|
5387 | * @param {*} sourceValue The source object property value.
|
5388 | * @param {string} key The key associated with the object and source values.
|
5389 | * @param {Object} object The destination object.
|
5390 | * @returns {*} Returns the value to assign to the destination object.
|
5391 | */
|
5392 | function assignOwnDefaults(objectValue, sourceValue, key, object) {
|
5393 | return (objectValue === undefined || !hasOwnProperty.call(object, key))
|
5394 | ? sourceValue
|
5395 | : objectValue;
|
5396 | }
|
5397 |
|
5398 | /**
|
5399 | * A specialized version of `_.assign` for customizing assigned values without
|
5400 | * support for argument juggling, multiple sources, and `this` binding `customizer`
|
5401 | * functions.
|
5402 | *
|
5403 | * @private
|
5404 | * @param {Object} object The destination object.
|
5405 | * @param {Object} source The source object.
|
5406 | * @param {Function} customizer The function to customize assigned values.
|
5407 | * @returns {Object} Returns `object`.
|
5408 | */
|
5409 | function assignWith(object, source, customizer) {
|
5410 | var index = -1,
|
5411 | props = keys(source),
|
5412 | length = props.length;
|
5413 |
|
5414 | while (++index < length) {
|
5415 | var key = props[index],
|
5416 | value = object[key],
|
5417 | result = customizer(value, source[key], key, object, source);
|
5418 |
|
5419 | if ((result === result ? (result !== value) : (value === value)) ||
|
5420 | (value === undefined && !(key in object))) {
|
5421 | object[key] = result;
|
5422 | }
|
5423 | }
|
5424 | return object;
|
5425 | }
|
5426 |
|
5427 | /**
|
5428 | * The base implementation of `_.assign` without support for argument juggling,
|
5429 | * multiple sources, and `customizer` functions.
|
5430 | *
|
5431 | * @private
|
5432 | * @param {Object} object The destination object.
|
5433 | * @param {Object} source The source object.
|
5434 | * @returns {Object} Returns `object`.
|
5435 | */
|
5436 | function baseAssign(object, source) {
|
5437 | return source == null
|
5438 | ? object
|
5439 | : baseCopy(source, keys(source), object);
|
5440 | }
|
5441 |
|
5442 | /**
|
5443 | * The base implementation of `_.at` without support for string collections
|
5444 | * and individual key arguments.
|
5445 | *
|
5446 | * @private
|
5447 | * @param {Array|Object} collection The collection to iterate over.
|
5448 | * @param {number[]|string[]} props The property names or indexes of elements to pick.
|
5449 | * @returns {Array} Returns the new array of picked elements.
|
5450 | */
|
5451 | function baseAt(collection, props) {
|
5452 | var index = -1,
|
5453 | isNil = collection == null,
|
5454 | isArr = !isNil && isArrayLike(collection),
|
5455 | length = isArr ? collection.length : 0,
|
5456 | propsLength = props.length,
|
5457 | result = Array(propsLength);
|
5458 |
|
5459 | while(++index < propsLength) {
|
5460 | var key = props[index];
|
5461 | if (isArr) {
|
5462 | result[index] = isIndex(key, length) ? collection[key] : undefined;
|
5463 | } else {
|
5464 | result[index] = isNil ? undefined : collection[key];
|
5465 | }
|
5466 | }
|
5467 | return result;
|
5468 | }
|
5469 |
|
5470 | /**
|
5471 | * Copies properties of `source` to `object`.
|
5472 | *
|
5473 | * @private
|
5474 | * @param {Object} source The object to copy properties from.
|
5475 | * @param {Array} props The property names to copy.
|
5476 | * @param {Object} [object={}] The object to copy properties to.
|
5477 | * @returns {Object} Returns `object`.
|
5478 | */
|
5479 | function baseCopy(source, props, object) {
|
5480 | object || (object = {});
|
5481 |
|
5482 | var index = -1,
|
5483 | length = props.length;
|
5484 |
|
5485 | while (++index < length) {
|
5486 | var key = props[index];
|
5487 | object[key] = source[key];
|
5488 | }
|
5489 | return object;
|
5490 | }
|
5491 |
|
5492 | /**
|
5493 | * The base implementation of `_.callback` which supports specifying the
|
5494 | * number of arguments to provide to `func`.
|
5495 | *
|
5496 | * @private
|
5497 | * @param {*} [func=_.identity] The value to convert to a callback.
|
5498 | * @param {*} [thisArg] The `this` binding of `func`.
|
5499 | * @param {number} [argCount] The number of arguments to provide to `func`.
|
5500 | * @returns {Function} Returns the callback.
|
5501 | */
|
5502 | function baseCallback(func, thisArg, argCount) {
|
5503 | var type = typeof func;
|
5504 | if (type == 'function') {
|
5505 | return thisArg === undefined
|
5506 | ? func
|
5507 | : bindCallback(func, thisArg, argCount);
|
5508 | }
|
5509 | if (func == null) {
|
5510 | return identity;
|
5511 | }
|
5512 | if (type == 'object') {
|
5513 | return baseMatches(func);
|
5514 | }
|
5515 | return thisArg === undefined
|
5516 | ? property(func)
|
5517 | : baseMatchesProperty(func, thisArg);
|
5518 | }
|
5519 |
|
5520 | /**
|
5521 | * The base implementation of `_.clone` without support for argument juggling
|
5522 | * and `this` binding `customizer` functions.
|
5523 | *
|
5524 | * @private
|
5525 | * @param {*} value The value to clone.
|
5526 | * @param {boolean} [isDeep] Specify a deep clone.
|
5527 | * @param {Function} [customizer] The function to customize cloning values.
|
5528 | * @param {string} [key] The key of `value`.
|
5529 | * @param {Object} [object] The object `value` belongs to.
|
5530 | * @param {Array} [stackA=[]] Tracks traversed source objects.
|
5531 | * @param {Array} [stackB=[]] Associates clones with source counterparts.
|
5532 | * @returns {*} Returns the cloned value.
|
5533 | */
|
5534 | function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
|
5535 | var result;
|
5536 | if (customizer) {
|
5537 | result = object ? customizer(value, key, object) : customizer(value);
|
5538 | }
|
5539 | if (result !== undefined) {
|
5540 | return result;
|
5541 | }
|
5542 | if (!isObject(value)) {
|
5543 | return value;
|
5544 | }
|
5545 | var isArr = isArray(value);
|
5546 | if (isArr) {
|
5547 | result = initCloneArray(value);
|
5548 | if (!isDeep) {
|
5549 | return arrayCopy(value, result);
|
5550 | }
|
5551 | } else {
|
5552 | var tag = objToString.call(value),
|
5553 | isFunc = tag == funcTag;
|
5554 |
|
5555 | if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
|
5556 | result = initCloneObject(isFunc ? {} : value);
|
5557 | if (!isDeep) {
|
5558 | return baseAssign(result, value);
|
5559 | }
|
5560 | } else {
|
5561 | return cloneableTags[tag]
|
5562 | ? initCloneByTag(value, tag, isDeep)
|
5563 | : (object ? value : {});
|
5564 | }
|
5565 | }
|
5566 | // Check for circular references and return its corresponding clone.
|
5567 | stackA || (stackA = []);
|
5568 | stackB || (stackB = []);
|
5569 |
|
5570 | var length = stackA.length;
|
5571 | while (length--) {
|
5572 | if (stackA[length] == value) {
|
5573 | return stackB[length];
|
5574 | }
|
5575 | }
|
5576 | // Add the source value to the stack of traversed objects and associate it with its clone.
|
5577 | stackA.push(value);
|
5578 | stackB.push(result);
|
5579 |
|
5580 | // Recursively populate clone (susceptible to call stack limits).
|
5581 | (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
|
5582 | result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
|
5583 | });
|
5584 | return result;
|
5585 | }
|
5586 |
|
5587 | /**
|
5588 | * The base implementation of `_.create` without support for assigning
|
5589 | * properties to the created object.
|
5590 | *
|
5591 | * @private
|
5592 | * @param {Object} prototype The object to inherit from.
|
5593 | * @returns {Object} Returns the new object.
|
5594 | */
|
5595 | var baseCreate = (function() {
|
5596 | function object() {}
|
5597 | return function(prototype) {
|
5598 | if (isObject(prototype)) {
|
5599 | object.prototype = prototype;
|
5600 | var result = new object;
|
5601 | object.prototype = undefined;
|
5602 | }
|
5603 | return result || {};
|
5604 | };
|
5605 | }());
|
5606 |
|
5607 | /**
|
5608 | * The base implementation of `_.delay` and `_.defer` which accepts an index
|
5609 | * of where to slice the arguments to provide to `func`.
|
5610 | *
|
5611 | * @private
|
5612 | * @param {Function} func The function to delay.
|
5613 | * @param {number} wait The number of milliseconds to delay invocation.
|
5614 | * @param {Object} args The arguments provide to `func`.
|
5615 | * @returns {number} Returns the timer id.
|
5616 | */
|
5617 | function baseDelay(func, wait, args) {
|
5618 | if (typeof func != 'function') {
|
5619 | throw new TypeError(FUNC_ERROR_TEXT);
|
5620 | }
|
5621 | return setTimeout(function() { func.apply(undefined, args); }, wait);
|
5622 | }
|
5623 |
|
5624 | /**
|
5625 | * The base implementation of `_.difference` which accepts a single array
|
5626 | * of values to exclude.
|
5627 | *
|
5628 | * @private
|
5629 | * @param {Array} array The array to inspect.
|
5630 | * @param {Array} values The values to exclude.
|
5631 | * @returns {Array} Returns the new array of filtered values.
|
5632 | */
|
5633 | function baseDifference(array, values) {
|
5634 | var length = array ? array.length : 0,
|
5635 | result = [];
|
5636 |
|
5637 | if (!length) {
|
5638 | return result;
|
5639 | }
|
5640 | var index = -1,
|
5641 | indexOf = getIndexOf(),
|
5642 | isCommon = indexOf == baseIndexOf,
|
5643 | cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null,
|
5644 | valuesLength = values.length;
|
5645 |
|
5646 | if (cache) {
|
5647 | indexOf = cacheIndexOf;
|
5648 | isCommon = false;
|
5649 | values = cache;
|
5650 | }
|
5651 | outer:
|
5652 | while (++index < length) {
|
5653 | var value = array[index];
|
5654 |
|
5655 | if (isCommon && value === value) {
|
5656 | var valuesIndex = valuesLength;
|
5657 | while (valuesIndex--) {
|
5658 | if (values[valuesIndex] === value) {
|
5659 | continue outer;
|
5660 | }
|
5661 | }
|
5662 | result.push(value);
|
5663 | }
|
5664 | else if (indexOf(values, value, 0) < 0) {
|
5665 | result.push(value);
|
5666 | }
|
5667 | }
|
5668 | return result;
|
5669 | }
|
5670 |
|
5671 | /**
|
5672 | * The base implementation of `_.forEach` without support for callback
|
5673 | * shorthands and `this` binding.
|
5674 | *
|
5675 | * @private
|
5676 | * @param {Array|Object|string} collection The collection to iterate over.
|
5677 | * @param {Function} iteratee The function invoked per iteration.
|
5678 | * @returns {Array|Object|string} Returns `collection`.
|
5679 | */
|
5680 | var baseEach = createBaseEach(baseForOwn);
|
5681 |
|
5682 | /**
|
5683 | * The base implementation of `_.forEachRight` without support for callback
|
5684 | * shorthands and `this` binding.
|
5685 | *
|
5686 | * @private
|
5687 | * @param {Array|Object|string} collection The collection to iterate over.
|
5688 | * @param {Function} iteratee The function invoked per iteration.
|
5689 | * @returns {Array|Object|string} Returns `collection`.
|
5690 | */
|
5691 | var baseEachRight = createBaseEach(baseForOwnRight, true);
|
5692 |
|
5693 | /**
|
5694 | * The base implementation of `_.every` without support for callback
|
5695 | * shorthands and `this` binding.
|
5696 | *
|
5697 | * @private
|
5698 | * @param {Array|Object|string} collection The collection to iterate over.
|
5699 | * @param {Function} predicate The function invoked per iteration.
|
5700 | * @returns {boolean} Returns `true` if all elements pass the predicate check,
|
5701 | * else `false`
|
5702 | */
|
5703 | function baseEvery(collection, predicate) {
|
5704 | var result = true;
|
5705 | baseEach(collection, function(value, index, collection) {
|
5706 | result = !!predicate(value, index, collection);
|
5707 | return result;
|
5708 | });
|
5709 | return result;
|
5710 | }
|
5711 |
|
5712 | /**
|
5713 | * Gets the extremum value of `collection` invoking `iteratee` for each value
|
5714 | * in `collection` to generate the criterion by which the value is ranked.
|
5715 | * The `iteratee` is invoked with three arguments: (value, index|key, collection).
|
5716 | *
|
5717 | * @private
|
5718 | * @param {Array|Object|string} collection The collection to iterate over.
|
5719 | * @param {Function} iteratee The function invoked per iteration.
|
5720 | * @param {Function} comparator The function used to compare values.
|
5721 | * @param {*} exValue The initial extremum value.
|
5722 | * @returns {*} Returns the extremum value.
|
5723 | */
|
5724 | function baseExtremum(collection, iteratee, comparator, exValue) {
|
5725 | var computed = exValue,
|
5726 | result = computed;
|
5727 |
|
5728 | baseEach(collection, function(value, index, collection) {
|
5729 | var current = +iteratee(value, index, collection);
|
5730 | if (comparator(current, computed) || (current === exValue && current === result)) {
|
5731 | computed = current;
|
5732 | result = value;
|
5733 | }
|
5734 | });
|
5735 | return result;
|
5736 | }
|
5737 |
|
5738 | /**
|
5739 | * The base implementation of `_.fill` without an iteratee call guard.
|
5740 | *
|
5741 | * @private
|
5742 | * @param {Array} array The array to fill.
|
5743 | * @param {*} value The value to fill `array` with.
|
5744 | * @param {number} [start=0] The start position.
|
5745 | * @param {number} [end=array.length] The end position.
|
5746 | * @returns {Array} Returns `array`.
|
5747 | */
|
5748 | function baseFill(array, value, start, end) {
|
5749 | var length = array.length;
|
5750 |
|
5751 | start = start == null ? 0 : (+start || 0);
|
5752 | if (start < 0) {
|
5753 | start = -start > length ? 0 : (length + start);
|
5754 | }
|
5755 | end = (end === undefined || end > length) ? length : (+end || 0);
|
5756 | if (end < 0) {
|
5757 | end += length;
|
5758 | }
|
5759 | length = start > end ? 0 : (end >>> 0);
|
5760 | start >>>= 0;
|
5761 |
|
5762 | while (start < length) {
|
5763 | array[start++] = value;
|
5764 | }
|
5765 | return array;
|
5766 | }
|
5767 |
|
5768 | /**
|
5769 | * The base implementation of `_.filter` without support for callback
|
5770 | * shorthands and `this` binding.
|
5771 | *
|
5772 | * @private
|
5773 | * @param {Array|Object|string} collection The collection to iterate over.
|
5774 | * @param {Function} predicate The function invoked per iteration.
|
5775 | * @returns {Array} Returns the new filtered array.
|
5776 | */
|
5777 | function baseFilter(collection, predicate) {
|
5778 | var result = [];
|
5779 | baseEach(collection, function(value, index, collection) {
|
5780 | if (predicate(value, index, collection)) {
|
5781 | result.push(value);
|
5782 | }
|
5783 | });
|
5784 | return result;
|
5785 | }
|
5786 |
|
5787 | /**
|
5788 | * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
|
5789 | * without support for callback shorthands and `this` binding, which iterates
|
5790 | * over `collection` using the provided `eachFunc`.
|
5791 | *
|
5792 | * @private
|
5793 | * @param {Array|Object|string} collection The collection to search.
|
5794 | * @param {Function} predicate The function invoked per iteration.
|
5795 | * @param {Function} eachFunc The function to iterate over `collection`.
|
5796 | * @param {boolean} [retKey] Specify returning the key of the found element
|
5797 | * instead of the element itself.
|
5798 | * @returns {*} Returns the found element or its key, else `undefined`.
|
5799 | */
|
5800 | function baseFind(collection, predicate, eachFunc, retKey) {
|
5801 | var result;
|
5802 | eachFunc(collection, function(value, key, collection) {
|
5803 | if (predicate(value, key, collection)) {
|
5804 | result = retKey ? key : value;
|
5805 | return false;
|
5806 | }
|
5807 | });
|
5808 | return result;
|
5809 | }
|
5810 |
|
5811 | /**
|
5812 | * The base implementation of `_.flatten` with added support for restricting
|
5813 | * flattening and specifying the start index.
|
5814 | *
|
5815 | * @private
|
5816 | * @param {Array} array The array to flatten.
|
5817 | * @param {boolean} [isDeep] Specify a deep flatten.
|
5818 | * @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
|
5819 | * @param {Array} [result=[]] The initial result value.
|
5820 | * @returns {Array} Returns the new flattened array.
|
5821 | */
|
5822 | function baseFlatten(array, isDeep, isStrict, result) {
|
5823 | result || (result = []);
|
5824 |
|
5825 | var index = -1,
|
5826 | length = array.length;
|
5827 |
|
5828 | while (++index < length) {
|
5829 | var value = array[index];
|
5830 | if (isObjectLike(value) && isArrayLike(value) &&
|
5831 | (isStrict || isArray(value) || isArguments(value))) {
|
5832 | if (isDeep) {
|
5833 | // Recursively flatten arrays (susceptible to call stack limits).
|
5834 | baseFlatten(value, isDeep, isStrict, result);
|
5835 | } else {
|
5836 | arrayPush(result, value);
|
5837 | }
|
5838 | } else if (!isStrict) {
|
5839 | result[result.length] = value;
|
5840 | }
|
5841 | }
|
5842 | return result;
|
5843 | }
|
5844 |
|
5845 | /**
|
5846 | * The base implementation of `baseForIn` and `baseForOwn` which iterates
|
5847 | * over `object` properties returned by `keysFunc` invoking `iteratee` for
|
5848 | * each property. Iteratee functions may exit iteration early by explicitly
|
5849 | * returning `false`.
|
5850 | *
|
5851 | * @private
|
5852 | * @param {Object} object The object to iterate over.
|
5853 | * @param {Function} iteratee The function invoked per iteration.
|
5854 | * @param {Function} keysFunc The function to get the keys of `object`.
|
5855 | * @returns {Object} Returns `object`.
|
5856 | */
|
5857 | var baseFor = createBaseFor();
|
5858 |
|
5859 | /**
|
5860 | * This function is like `baseFor` except that it iterates over properties
|
5861 | * in the opposite order.
|
5862 | *
|
5863 | * @private
|
5864 | * @param {Object} object The object to iterate over.
|
5865 | * @param {Function} iteratee The function invoked per iteration.
|
5866 | * @param {Function} keysFunc The function to get the keys of `object`.
|
5867 | * @returns {Object} Returns `object`.
|
5868 | */
|
5869 | var baseForRight = createBaseFor(true);
|
5870 |
|
5871 | /**
|
5872 | * The base implementation of `_.forIn` without support for callback
|
5873 | * shorthands and `this` binding.
|
5874 | *
|
5875 | * @private
|
5876 | * @param {Object} object The object to iterate over.
|
5877 | * @param {Function} iteratee The function invoked per iteration.
|
5878 | * @returns {Object} Returns `object`.
|
5879 | */
|
5880 | function baseForIn(object, iteratee) {
|
5881 | return baseFor(object, iteratee, keysIn);
|
5882 | }
|
5883 |
|
5884 | /**
|
5885 | * The base implementation of `_.forOwn` without support for callback
|
5886 | * shorthands and `this` binding.
|
5887 | *
|
5888 | * @private
|
5889 | * @param {Object} object The object to iterate over.
|
5890 | * @param {Function} iteratee The function invoked per iteration.
|
5891 | * @returns {Object} Returns `object`.
|
5892 | */
|
5893 | function baseForOwn(object, iteratee) {
|
5894 | return baseFor(object, iteratee, keys);
|
5895 | }
|
5896 |
|
5897 | /**
|
5898 | * The base implementation of `_.forOwnRight` without support for callback
|
5899 | * shorthands and `this` binding.
|
5900 | *
|
5901 | * @private
|
5902 | * @param {Object} object The object to iterate over.
|
5903 | * @param {Function} iteratee The function invoked per iteration.
|
5904 | * @returns {Object} Returns `object`.
|
5905 | */
|
5906 | function baseForOwnRight(object, iteratee) {
|
5907 | return baseForRight(object, iteratee, keys);
|
5908 | }
|
5909 |
|
5910 | /**
|
5911 | * The base implementation of `_.functions` which creates an array of
|
5912 | * `object` function property names filtered from those provided.
|
5913 | *
|
5914 | * @private
|
5915 | * @param {Object} object The object to inspect.
|
5916 | * @param {Array} props The property names to filter.
|
5917 | * @returns {Array} Returns the new array of filtered property names.
|
5918 | */
|
5919 | function baseFunctions(object, props) {
|
5920 | var index = -1,
|
5921 | length = props.length,
|
5922 | resIndex = -1,
|
5923 | result = [];
|
5924 |
|
5925 | while (++index < length) {
|
5926 | var key = props[index];
|
5927 | if (isFunction(object[key])) {
|
5928 | result[++resIndex] = key;
|
5929 | }
|
5930 | }
|
5931 | return result;
|
5932 | }
|
5933 |
|
5934 | /**
|
5935 | * The base implementation of `get` without support for string paths
|
5936 | * and default values.
|
5937 | *
|
5938 | * @private
|
5939 | * @param {Object} object The object to query.
|
5940 | * @param {Array} path The path of the property to get.
|
5941 | * @param {string} [pathKey] The key representation of path.
|
5942 | * @returns {*} Returns the resolved value.
|
5943 | */
|
5944 | function baseGet(object, path, pathKey) {
|
5945 | if (object == null) {
|
5946 | return;
|
5947 | }
|
5948 | if (pathKey !== undefined && pathKey in toObject(object)) {
|
5949 | path = [pathKey];
|
5950 | }
|
5951 | var index = 0,
|
5952 | length = path.length;
|
5953 |
|
5954 | while (object != null && index < length) {
|
5955 | object = object[path[index++]];
|
5956 | }
|
5957 | return (index && index == length) ? object : undefined;
|
5958 | }
|
5959 |
|
5960 | /**
|
5961 | * The base implementation of `_.isEqual` without support for `this` binding
|
5962 | * `customizer` functions.
|
5963 | *
|
5964 | * @private
|
5965 | * @param {*} value The value to compare.
|
5966 | * @param {*} other The other value to compare.
|
5967 | * @param {Function} [customizer] The function to customize comparing values.
|
5968 | * @param {boolean} [isLoose] Specify performing partial comparisons.
|
5969 | * @param {Array} [stackA] Tracks traversed `value` objects.
|
5970 | * @param {Array} [stackB] Tracks traversed `other` objects.
|
5971 | * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
|
5972 | */
|
5973 | function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
|
5974 | if (value === other) {
|
5975 | return true;
|
5976 | }
|
5977 | if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
|
5978 | return value !== value && other !== other;
|
5979 | }
|
5980 | return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
|
5981 | }
|
5982 |
|
5983 | /**
|
5984 | * A specialized version of `baseIsEqual` for arrays and objects which performs
|
5985 | * deep comparisons and tracks traversed objects enabling objects with circular
|
5986 | * references to be compared.
|
5987 | *
|
5988 | * @private
|
5989 | * @param {Object} object The object to compare.
|
5990 | * @param {Object} other The other object to compare.
|
5991 | * @param {Function} equalFunc The function to determine equivalents of values.
|
5992 | * @param {Function} [customizer] The function to customize comparing objects.
|
5993 | * @param {boolean} [isLoose] Specify performing partial comparisons.
|
5994 | * @param {Array} [stackA=[]] Tracks traversed `value` objects.
|
5995 | * @param {Array} [stackB=[]] Tracks traversed `other` objects.
|
5996 | * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
|
5997 | */
|
5998 | function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
|
5999 | var objIsArr = isArray(object),
|
6000 | othIsArr = isArray(other),
|
6001 | objTag = arrayTag,
|
6002 | othTag = arrayTag;
|
6003 |
|
6004 | if (!objIsArr) {
|
6005 | objTag = objToString.call(object);
|
6006 | if (objTag == argsTag) {
|
6007 | objTag = objectTag;
|
6008 | } else if (objTag != objectTag) {
|
6009 | objIsArr = isTypedArray(object);
|
6010 | }
|
6011 | }
|
6012 | if (!othIsArr) {
|
6013 | othTag = objToString.call(other);
|
6014 | if (othTag == argsTag) {
|
6015 | othTag = objectTag;
|
6016 | } else if (othTag != objectTag) {
|
6017 | othIsArr = isTypedArray(other);
|
6018 | }
|
6019 | }
|
6020 | var objIsObj = objTag == objectTag,
|
6021 | othIsObj = othTag == objectTag,
|
6022 | isSameTag = objTag == othTag;
|
6023 |
|
6024 | if (isSameTag && !(objIsArr || objIsObj)) {
|
6025 | return equalByTag(object, other, objTag);
|
6026 | }
|
6027 | if (!isLoose) {
|
6028 | var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
|
6029 | othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
|
6030 |
|
6031 | if (objIsWrapped || othIsWrapped) {
|
6032 | return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
|
6033 | }
|
6034 | }
|
6035 | if (!isSameTag) {
|
6036 | return false;
|
6037 | }
|
6038 | // Assume cyclic values are equal.
|
6039 | // For more information on detecting circular references see https://es5.github.io/#JO.
|
6040 | stackA || (stackA = []);
|
6041 | stackB || (stackB = []);
|
6042 |
|
6043 | var length = stackA.length;
|
6044 | while (length--) {
|
6045 | if (stackA[length] == object) {
|
6046 | return stackB[length] == other;
|
6047 | }
|
6048 | }
|
6049 | // Add `object` and `other` to the stack of traversed objects.
|
6050 | stackA.push(object);
|
6051 | stackB.push(other);
|
6052 |
|
6053 | var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
|
6054 |
|
6055 | stackA.pop();
|
6056 | stackB.pop();
|
6057 |
|
6058 | return result;
|
6059 | }
|
6060 |
|
6061 | /**
|
6062 | * The base implementation of `_.isMatch` without support for callback
|
6063 | * shorthands and `this` binding.
|
6064 | *
|
6065 | * @private
|
6066 | * @param {Object} object The object to inspect.
|
6067 | * @param {Array} matchData The propery names, values, and compare flags to match.
|
6068 | * @param {Function} [customizer] The function to customize comparing objects.
|
6069 | * @returns {boolean} Returns `true` if `object` is a match, else `false`.
|
6070 | */
|
6071 | function baseIsMatch(object, matchData, customizer) {
|
6072 | var index = matchData.length,
|
6073 | length = index,
|
6074 | noCustomizer = !customizer;
|
6075 |
|
6076 | if (object == null) {
|
6077 | return !length;
|
6078 | }
|
6079 | object = toObject(object);
|
6080 | while (index--) {
|
6081 | var data = matchData[index];
|
6082 | if ((noCustomizer && data[2])
|
6083 | ? data[1] !== object[data[0]]
|
6084 | : !(data[0] in object)
|
6085 | ) {
|
6086 | return false;
|
6087 | }
|
6088 | }
|
6089 | while (++index < length) {
|
6090 | data = matchData[index];
|
6091 | var key = data[0],
|
6092 | objValue = object[key],
|
6093 | srcValue = data[1];
|
6094 |
|
6095 | if (noCustomizer && data[2]) {
|
6096 | if (objValue === undefined && !(key in object)) {
|
6097 | return false;
|
6098 | }
|
6099 | } else {
|
6100 | var result = customizer ? customizer(objValue, srcValue, key) : undefined;
|
6101 | if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
|
6102 | return false;
|
6103 | }
|
6104 | }
|
6105 | }
|
6106 | return true;
|
6107 | }
|
6108 |
|
6109 | /**
|
6110 | * The base implementation of `_.map` without support for callback shorthands
|
6111 | * and `this` binding.
|
6112 | *
|
6113 | * @private
|
6114 | * @param {Array|Object|string} collection The collection to iterate over.
|
6115 | * @param {Function} iteratee The function invoked per iteration.
|
6116 | * @returns {Array} Returns the new mapped array.
|
6117 | */
|
6118 | function baseMap(collection, iteratee) {
|
6119 | var index = -1,
|
6120 | result = isArrayLike(collection) ? Array(collection.length) : [];
|
6121 |
|
6122 | baseEach(collection, function(value, key, collection) {
|
6123 | result[++index] = iteratee(value, key, collection);
|
6124 | });
|
6125 | return result;
|
6126 | }
|
6127 |
|
6128 | /**
|
6129 | * The base implementation of `_.matches` which does not clone `source`.
|
6130 | *
|
6131 | * @private
|
6132 | * @param {Object} source The object of property values to match.
|
6133 | * @returns {Function} Returns the new function.
|
6134 | */
|
6135 | function baseMatches(source) {
|
6136 | var matchData = getMatchData(source);
|
6137 | if (matchData.length == 1 && matchData[0][2]) {
|
6138 | var key = matchData[0][0],
|
6139 | value = matchData[0][1];
|
6140 |
|
6141 | return function(object) {
|
6142 | if (object == null) {
|
6143 | return false;
|
6144 | }
|
6145 | return object[key] === value && (value !== undefined || (key in toObject(object)));
|
6146 | };
|
6147 | }
|
6148 | return function(object) {
|
6149 | return baseIsMatch(object, matchData);
|
6150 | };
|
6151 | }
|
6152 |
|
6153 | /**
|
6154 | * The base implementation of `_.matchesProperty` which does not clone `srcValue`.
|
6155 | *
|
6156 | * @private
|
6157 | * @param {string} path The path of the property to get.
|
6158 | * @param {*} srcValue The value to compare.
|
6159 | * @returns {Function} Returns the new function.
|
6160 | */
|
6161 | function baseMatchesProperty(path, srcValue) {
|
6162 | var isArr = isArray(path),
|
6163 | isCommon = isKey(path) && isStrictComparable(srcValue),
|
6164 | pathKey = (path + '');
|
6165 |
|
6166 | path = toPath(path);
|
6167 | return function(object) {
|
6168 | if (object == null) {
|
6169 | return false;
|
6170 | }
|
6171 | var key = pathKey;
|
6172 | object = toObject(object);
|
6173 | if ((isArr || !isCommon) && !(key in object)) {
|
6174 | object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
|
6175 | if (object == null) {
|
6176 | return false;
|
6177 | }
|
6178 | key = last(path);
|
6179 | object = toObject(object);
|
6180 | }
|
6181 | return object[key] === srcValue
|
6182 | ? (srcValue !== undefined || (key in object))
|
6183 | : baseIsEqual(srcValue, object[key], undefined, true);
|
6184 | };
|
6185 | }
|
6186 |
|
6187 | /**
|
6188 | * The base implementation of `_.merge` without support for argument juggling,
|
6189 | * multiple sources, and `this` binding `customizer` functions.
|
6190 | *
|
6191 | * @private
|
6192 | * @param {Object} object The destination object.
|
6193 | * @param {Object} source The source object.
|
6194 | * @param {Function} [customizer] The function to customize merged values.
|
6195 | * @param {Array} [stackA=[]] Tracks traversed source objects.
|
6196 | * @param {Array} [stackB=[]] Associates values with source counterparts.
|
6197 | * @returns {Object} Returns `object`.
|
6198 | */
|
6199 | function baseMerge(object, source, customizer, stackA, stackB) {
|
6200 | if (!isObject(object)) {
|
6201 | return object;
|
6202 | }
|
6203 | var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
|
6204 | props = isSrcArr ? undefined : keys(source);
|
6205 |
|
6206 | arrayEach(props || source, function(srcValue, key) {
|
6207 | if (props) {
|
6208 | key = srcValue;
|
6209 | srcValue = source[key];
|
6210 | }
|
6211 | if (isObjectLike(srcValue)) {
|
6212 | stackA || (stackA = []);
|
6213 | stackB || (stackB = []);
|
6214 | baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
|
6215 | }
|
6216 | else {
|
6217 | var value = object[key],
|
6218 | result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
|
6219 | isCommon = result === undefined;
|
6220 |
|
6221 | if (isCommon) {
|
6222 | result = srcValue;
|
6223 | }
|
6224 | if ((result !== undefined || (isSrcArr && !(key in object))) &&
|
6225 | (isCommon || (result === result ? (result !== value) : (value === value)))) {
|
6226 | object[key] = result;
|
6227 | }
|
6228 | }
|
6229 | });
|
6230 | return object;
|
6231 | }
|
6232 |
|
6233 | /**
|
6234 | * A specialized version of `baseMerge` for arrays and objects which performs
|
6235 | * deep merges and tracks traversed objects enabling objects with circular
|
6236 | * references to be merged.
|
6237 | *
|
6238 | * @private
|
6239 | * @param {Object} object The destination object.
|
6240 | * @param {Object} source The source object.
|
6241 | * @param {string} key The key of the value to merge.
|
6242 | * @param {Function} mergeFunc The function to merge values.
|
6243 | * @param {Function} [customizer] The function to customize merged values.
|
6244 | * @param {Array} [stackA=[]] Tracks traversed source objects.
|
6245 | * @param {Array} [stackB=[]] Associates values with source counterparts.
|
6246 | * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
|
6247 | */
|
6248 | function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
|
6249 | var length = stackA.length,
|
6250 | srcValue = source[key];
|
6251 |
|
6252 | while (length--) {
|
6253 | if (stackA[length] == srcValue) {
|
6254 | object[key] = stackB[length];
|
6255 | return;
|
6256 | }
|
6257 | }
|
6258 | var value = object[key],
|
6259 | result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
|
6260 | isCommon = result === undefined;
|
6261 |
|
6262 | if (isCommon) {
|
6263 | result = srcValue;
|
6264 | if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
|
6265 | result = isArray(value)
|
6266 | ? value
|
6267 | : (isArrayLike(value) ? arrayCopy(value) : []);
|
6268 | }
|
6269 | else if (isPlainObject(srcValue) || isArguments(srcValue)) {
|
6270 | result = isArguments(value)
|
6271 | ? toPlainObject(value)
|
6272 | : (isPlainObject(value) ? value : {});
|
6273 | }
|
6274 | else {
|
6275 | isCommon = false;
|
6276 | }
|
6277 | }
|
6278 | // Add the source value to the stack of traversed objects and associate
|
6279 | // it with its merged value.
|
6280 | stackA.push(srcValue);
|
6281 | stackB.push(result);
|
6282 |
|
6283 | if (isCommon) {
|
6284 | // Recursively merge objects and arrays (susceptible to call stack limits).
|
6285 | object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
|
6286 | } else if (result === result ? (result !== value) : (value === value)) {
|
6287 | object[key] = result;
|
6288 | }
|
6289 | }
|
6290 |
|
6291 | /**
|
6292 | * The base implementation of `_.property` without support for deep paths.
|
6293 | *
|
6294 | * @private
|
6295 | * @param {string} key The key of the property to get.
|
6296 | * @returns {Function} Returns the new function.
|
6297 | */
|
6298 | function baseProperty(key) {
|
6299 | return function(object) {
|
6300 | return object == null ? undefined : object[key];
|
6301 | };
|
6302 | }
|
6303 |
|
6304 | /**
|
6305 | * A specialized version of `baseProperty` which supports deep paths.
|
6306 | *
|
6307 | * @private
|
6308 | * @param {Array|string} path The path of the property to get.
|
6309 | * @returns {Function} Returns the new function.
|
6310 | */
|
6311 | function basePropertyDeep(path) {
|
6312 | var pathKey = (path + '');
|
6313 | path = toPath(path);
|
6314 | return function(object) {
|
6315 | return baseGet(object, path, pathKey);
|
6316 | };
|
6317 | }
|
6318 |
|
6319 | /**
|
6320 | * The base implementation of `_.pullAt` without support for individual
|
6321 | * index arguments and capturing the removed elements.
|
6322 | *
|
6323 | * @private
|
6324 | * @param {Array} array The array to modify.
|
6325 | * @param {number[]} indexes The indexes of elements to remove.
|
6326 | * @returns {Array} Returns `array`.
|
6327 | */
|
6328 | function basePullAt(array, indexes) {
|
6329 | var length = array ? indexes.length : 0;
|
6330 | while (length--) {
|
6331 | var index = indexes[length];
|
6332 | if (index != previous && isIndex(index)) {
|
6333 | var previous = index;
|
6334 | splice.call(array, index, 1);
|
6335 | }
|
6336 | }
|
6337 | return array;
|
6338 | }
|
6339 |
|
6340 | /**
|
6341 | * The base implementation of `_.random` without support for argument juggling
|
6342 | * and returning floating-point numbers.
|
6343 | *
|
6344 | * @private
|
6345 | * @param {number} min The minimum possible value.
|
6346 | * @param {number} max The maximum possible value.
|
6347 | * @returns {number} Returns the random number.
|
6348 | */
|
6349 | function baseRandom(min, max) {
|
6350 | return min + nativeFloor(nativeRandom() * (max - min + 1));
|
6351 | }
|
6352 |
|
6353 | /**
|
6354 | * The base implementation of `_.reduce` and `_.reduceRight` without support
|
6355 | * for callback shorthands and `this` binding, which iterates over `collection`
|
6356 | * using the provided `eachFunc`.
|
6357 | *
|
6358 | * @private
|
6359 | * @param {Array|Object|string} collection The collection to iterate over.
|
6360 | * @param {Function} iteratee The function invoked per iteration.
|
6361 | * @param {*} accumulator The initial value.
|
6362 | * @param {boolean} initFromCollection Specify using the first or last element
|
6363 | * of `collection` as the initial value.
|
6364 | * @param {Function} eachFunc The function to iterate over `collection`.
|
6365 | * @returns {*} Returns the accumulated value.
|
6366 | */
|
6367 | function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
|
6368 | eachFunc(collection, function(value, index, collection) {
|
6369 | accumulator = initFromCollection
|
6370 | ? (initFromCollection = false, value)
|
6371 | : iteratee(accumulator, value, index, collection);
|
6372 | });
|
6373 | return accumulator;
|
6374 | }
|
6375 |
|
6376 | /**
|
6377 | * The base implementation of `setData` without support for hot loop detection.
|
6378 | *
|
6379 | * @private
|
6380 | * @param {Function} func The function to associate metadata with.
|
6381 | * @param {*} data The metadata.
|
6382 | * @returns {Function} Returns `func`.
|
6383 | */
|
6384 | var baseSetData = !metaMap ? identity : function(func, data) {
|
6385 | metaMap.set(func, data);
|
6386 | return func;
|
6387 | };
|
6388 |
|
6389 | /**
|
6390 | * The base implementation of `_.slice` without an iteratee call guard.
|
6391 | *
|
6392 | * @private
|
6393 | * @param {Array} array The array to slice.
|
6394 | * @param {number} [start=0] The start position.
|
6395 | * @param {number} [end=array.length] The end position.
|
6396 | * @returns {Array} Returns the slice of `array`.
|
6397 | */
|
6398 | function baseSlice(array, start, end) {
|
6399 | var index = -1,
|
6400 | length = array.length;
|
6401 |
|
6402 | start = start == null ? 0 : (+start || 0);
|
6403 | if (start < 0) {
|
6404 | start = -start > length ? 0 : (length + start);
|
6405 | }
|
6406 | end = (end === undefined || end > length) ? length : (+end || 0);
|
6407 | if (end < 0) {
|
6408 | end += length;
|
6409 | }
|
6410 | length = start > end ? 0 : ((end - start) >>> 0);
|
6411 | start >>>= 0;
|
6412 |
|
6413 | var result = Array(length);
|
6414 | while (++index < length) {
|
6415 | result[index] = array[index + start];
|
6416 | }
|
6417 | return result;
|
6418 | }
|
6419 |
|
6420 | /**
|
6421 | * The base implementation of `_.some` without support for callback shorthands
|
6422 | * and `this` binding.
|
6423 | *
|
6424 | * @private
|
6425 | * @param {Array|Object|string} collection The collection to iterate over.
|
6426 | * @param {Function} predicate The function invoked per iteration.
|
6427 | * @returns {boolean} Returns `true` if any element passes the predicate check,
|
6428 | * else `false`.
|
6429 | */
|
6430 | function baseSome(collection, predicate) {
|
6431 | var result;
|
6432 |
|
6433 | baseEach(collection, function(value, index, collection) {
|
6434 | result = predicate(value, index, collection);
|
6435 | return !result;
|
6436 | });
|
6437 | return !!result;
|
6438 | }
|
6439 |
|
6440 | /**
|
6441 | * The base implementation of `_.sortBy` which uses `comparer` to define
|
6442 | * the sort order of `array` and replaces criteria objects with their
|
6443 | * corresponding values.
|
6444 | *
|
6445 | * @private
|
6446 | * @param {Array} array The array to sort.
|
6447 | * @param {Function} comparer The function to define sort order.
|
6448 | * @returns {Array} Returns `array`.
|
6449 | */
|
6450 | function baseSortBy(array, comparer) {
|
6451 | var length = array.length;
|
6452 |
|
6453 | array.sort(comparer);
|
6454 | while (length--) {
|
6455 | array[length] = array[length].value;
|
6456 | }
|
6457 | return array;
|
6458 | }
|
6459 |
|
6460 | /**
|
6461 | * The base implementation of `_.sortByOrder` without param guards.
|
6462 | *
|
6463 | * @private
|
6464 | * @param {Array|Object|string} collection The collection to iterate over.
|
6465 | * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
|
6466 | * @param {boolean[]} orders The sort orders of `iteratees`.
|
6467 | * @returns {Array} Returns the new sorted array.
|
6468 | */
|
6469 | function baseSortByOrder(collection, iteratees, orders) {
|
6470 | var callback = getCallback(),
|
6471 | index = -1;
|
6472 |
|
6473 | iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); });
|
6474 |
|
6475 | var result = baseMap(collection, function(value) {
|
6476 | var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); });
|
6477 | return { 'criteria': criteria, 'index': ++index, 'value': value };
|
6478 | });
|
6479 |
|
6480 | return baseSortBy(result, function(object, other) {
|
6481 | return compareMultiple(object, other, orders);
|
6482 | });
|
6483 | }
|
6484 |
|
6485 | /**
|
6486 | * The base implementation of `_.sum` without support for callback shorthands
|
6487 | * and `this` binding.
|
6488 | *
|
6489 | * @private
|
6490 | * @param {Array|Object|string} collection The collection to iterate over.
|
6491 | * @param {Function} iteratee The function invoked per iteration.
|
6492 | * @returns {number} Returns the sum.
|
6493 | */
|
6494 | function baseSum(collection, iteratee) {
|
6495 | var result = 0;
|
6496 | baseEach(collection, function(value, index, collection) {
|
6497 | result += +iteratee(value, index, collection) || 0;
|
6498 | });
|
6499 | return result;
|
6500 | }
|
6501 |
|
6502 | /**
|
6503 | * The base implementation of `_.uniq` without support for callback shorthands
|
6504 | * and `this` binding.
|
6505 | *
|
6506 | * @private
|
6507 | * @param {Array} array The array to inspect.
|
6508 | * @param {Function} [iteratee] The function invoked per iteration.
|
6509 | * @returns {Array} Returns the new duplicate-value-free array.
|
6510 | */
|
6511 | function baseUniq(array, iteratee) {
|
6512 | var index = -1,
|
6513 | indexOf = getIndexOf(),
|
6514 | length = array.length,
|
6515 | isCommon = indexOf == baseIndexOf,
|
6516 | isLarge = isCommon && length >= LARGE_ARRAY_SIZE,
|
6517 | seen = isLarge ? createCache() : null,
|
6518 | result = [];
|
6519 |
|
6520 | if (seen) {
|
6521 | indexOf = cacheIndexOf;
|
6522 | isCommon = false;
|
6523 | } else {
|
6524 | isLarge = false;
|
6525 | seen = iteratee ? [] : result;
|
6526 | }
|
6527 | outer:
|
6528 | while (++index < length) {
|
6529 | var value = array[index],
|
6530 | computed = iteratee ? iteratee(value, index, array) : value;
|
6531 |
|
6532 | if (isCommon && value === value) {
|
6533 | var seenIndex = seen.length;
|
6534 | while (seenIndex--) {
|
6535 | if (seen[seenIndex] === computed) {
|
6536 | continue outer;
|
6537 | }
|
6538 | }
|
6539 | if (iteratee) {
|
6540 | seen.push(computed);
|
6541 | }
|
6542 | result.push(value);
|
6543 | }
|
6544 | else if (indexOf(seen, computed, 0) < 0) {
|
6545 | if (iteratee || isLarge) {
|
6546 | seen.push(computed);
|
6547 | }
|
6548 | result.push(value);
|
6549 | }
|
6550 | }
|
6551 | return result;
|
6552 | }
|
6553 |
|
6554 | /**
|
6555 | * The base implementation of `_.values` and `_.valuesIn` which creates an
|
6556 | * array of `object` property values corresponding to the property names
|
6557 | * of `props`.
|
6558 | *
|
6559 | * @private
|
6560 | * @param {Object} object The object to query.
|
6561 | * @param {Array} props The property names to get values for.
|
6562 | * @returns {Object} Returns the array of property values.
|
6563 | */
|
6564 | function baseValues(object, props) {
|
6565 | var index = -1,
|
6566 | length = props.length,
|
6567 | result = Array(length);
|
6568 |
|
6569 | while (++index < length) {
|
6570 | result[index] = object[props[index]];
|
6571 | }
|
6572 | return result;
|
6573 | }
|
6574 |
|
6575 | /**
|
6576 | * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
|
6577 | * and `_.takeWhile` without support for callback shorthands and `this` binding.
|
6578 | *
|
6579 | * @private
|
6580 | * @param {Array} array The array to query.
|
6581 | * @param {Function} predicate The function invoked per iteration.
|
6582 | * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
|
6583 | * @param {boolean} [fromRight] Specify iterating from right to left.
|
6584 | * @returns {Array} Returns the slice of `array`.
|
6585 | */
|
6586 | function baseWhile(array, predicate, isDrop, fromRight) {
|
6587 | var length = array.length,
|
6588 | index = fromRight ? length : -1;
|
6589 |
|
6590 | while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
|
6591 | return isDrop
|
6592 | ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
|
6593 | : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
|
6594 | }
|
6595 |
|
6596 | /**
|
6597 | * The base implementation of `wrapperValue` which returns the result of
|
6598 | * performing a sequence of actions on the unwrapped `value`, where each
|
6599 | * successive action is supplied the return value of the previous.
|
6600 | *
|
6601 | * @private
|
6602 | * @param {*} value The unwrapped value.
|
6603 | * @param {Array} actions Actions to peform to resolve the unwrapped value.
|
6604 | * @returns {*} Returns the resolved value.
|
6605 | */
|
6606 | function baseWrapperValue(value, actions) {
|
6607 | var result = value;
|
6608 | if (result instanceof LazyWrapper) {
|
6609 | result = result.value();
|
6610 | }
|
6611 | var index = -1,
|
6612 | length = actions.length;
|
6613 |
|
6614 | while (++index < length) {
|
6615 | var action = actions[index];
|
6616 | result = action.func.apply(action.thisArg, arrayPush([result], action.args));
|
6617 | }
|
6618 | return result;
|
6619 | }
|
6620 |
|
6621 | /**
|
6622 | * Performs a binary search of `array` to determine the index at which `value`
|
6623 | * should be inserted into `array` in order to maintain its sort order.
|
6624 | *
|
6625 | * @private
|
6626 | * @param {Array} array The sorted array to inspect.
|
6627 | * @param {*} value The value to evaluate.
|
6628 | * @param {boolean} [retHighest] Specify returning the highest qualified index.
|
6629 | * @returns {number} Returns the index at which `value` should be inserted
|
6630 | * into `array`.
|
6631 | */
|
6632 | function binaryIndex(array, value, retHighest) {
|
6633 | var low = 0,
|
6634 | high = array ? array.length : low;
|
6635 |
|
6636 | if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
|
6637 | while (low < high) {
|
6638 | var mid = (low + high) >>> 1,
|
6639 | computed = array[mid];
|
6640 |
|
6641 | if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
|
6642 | low = mid + 1;
|
6643 | } else {
|
6644 | high = mid;
|
6645 | }
|
6646 | }
|
6647 | return high;
|
6648 | }
|
6649 | return binaryIndexBy(array, value, identity, retHighest);
|
6650 | }
|
6651 |
|
6652 | /**
|
6653 | * This function is like `binaryIndex` except that it invokes `iteratee` for
|
6654 | * `value` and each element of `array` to compute their sort ranking. The
|
6655 | * iteratee is invoked with one argument; (value).
|
6656 | *
|
6657 | * @private
|
6658 | * @param {Array} array The sorted array to inspect.
|
6659 | * @param {*} value The value to evaluate.
|
6660 | * @param {Function} iteratee The function invoked per iteration.
|
6661 | * @param {boolean} [retHighest] Specify returning the highest qualified index.
|
6662 | * @returns {number} Returns the index at which `value` should be inserted
|
6663 | * into `array`.
|
6664 | */
|
6665 | function binaryIndexBy(array, value, iteratee, retHighest) {
|
6666 | value = iteratee(value);
|
6667 |
|
6668 | var low = 0,
|
6669 | high = array ? array.length : 0,
|
6670 | valIsNaN = value !== value,
|
6671 | valIsNull = value === null,
|
6672 | valIsUndef = value === undefined;
|
6673 |
|
6674 | while (low < high) {
|
6675 | var mid = nativeFloor((low + high) / 2),
|
6676 | computed = iteratee(array[mid]),
|
6677 | isDef = computed !== undefined,
|
6678 | isReflexive = computed === computed;
|
6679 |
|
6680 | if (valIsNaN) {
|
6681 | var setLow = isReflexive || retHighest;
|
6682 | } else if (valIsNull) {
|
6683 | setLow = isReflexive && isDef && (retHighest || computed != null);
|
6684 | } else if (valIsUndef) {
|
6685 | setLow = isReflexive && (retHighest || isDef);
|
6686 | } else if (computed == null) {
|
6687 | setLow = false;
|
6688 | } else {
|
6689 | setLow = retHighest ? (computed <= value) : (computed < value);
|
6690 | }
|
6691 | if (setLow) {
|
6692 | low = mid + 1;
|
6693 | } else {
|
6694 | high = mid;
|
6695 | }
|
6696 | }
|
6697 | return nativeMin(high, MAX_ARRAY_INDEX);
|
6698 | }
|
6699 |
|
6700 | /**
|
6701 | * A specialized version of `baseCallback` which only supports `this` binding
|
6702 | * and specifying the number of arguments to provide to `func`.
|
6703 | *
|
6704 | * @private
|
6705 | * @param {Function} func The function to bind.
|
6706 | * @param {*} thisArg The `this` binding of `func`.
|
6707 | * @param {number} [argCount] The number of arguments to provide to `func`.
|
6708 | * @returns {Function} Returns the callback.
|
6709 | */
|
6710 | function bindCallback(func, thisArg, argCount) {
|
6711 | if (typeof func != 'function') {
|
6712 | return identity;
|
6713 | }
|
6714 | if (thisArg === undefined) {
|
6715 | return func;
|
6716 | }
|
6717 | switch (argCount) {
|
6718 | case 1: return function(value) {
|
6719 | return func.call(thisArg, value);
|
6720 | };
|
6721 | case 3: return function(value, index, collection) {
|
6722 | return func.call(thisArg, value, index, collection);
|
6723 | };
|
6724 | case 4: return function(accumulator, value, index, collection) {
|
6725 | return func.call(thisArg, accumulator, value, index, collection);
|
6726 | };
|
6727 | case 5: return function(value, other, key, object, source) {
|
6728 | return func.call(thisArg, value, other, key, object, source);
|
6729 | };
|
6730 | }
|
6731 | return function() {
|
6732 | return func.apply(thisArg, arguments);
|
6733 | };
|
6734 | }
|
6735 |
|
6736 | /**
|
6737 | * Creates a clone of the given array buffer.
|
6738 | *
|
6739 | * @private
|
6740 | * @param {ArrayBuffer} buffer The array buffer to clone.
|
6741 | * @returns {ArrayBuffer} Returns the cloned array buffer.
|
6742 | */
|
6743 | function bufferClone(buffer) {
|
6744 | var result = new ArrayBuffer(buffer.byteLength),
|
6745 | view = new Uint8Array(result);
|
6746 |
|
6747 | view.set(new Uint8Array(buffer));
|
6748 | return result;
|
6749 | }
|
6750 |
|
6751 | /**
|
6752 | * Creates an array that is the composition of partially applied arguments,
|
6753 | * placeholders, and provided arguments into a single array of arguments.
|
6754 | *
|
6755 | * @private
|
6756 | * @param {Array|Object} args The provided arguments.
|
6757 | * @param {Array} partials The arguments to prepend to those provided.
|
6758 | * @param {Array} holders The `partials` placeholder indexes.
|
6759 | * @returns {Array} Returns the new array of composed arguments.
|
6760 | */
|
6761 | function composeArgs(args, partials, holders) {
|
6762 | var holdersLength = holders.length,
|
6763 | argsIndex = -1,
|
6764 | argsLength = nativeMax(args.length - holdersLength, 0),
|
6765 | leftIndex = -1,
|
6766 | leftLength = partials.length,
|
6767 | result = Array(leftLength + argsLength);
|
6768 |
|
6769 | while (++leftIndex < leftLength) {
|
6770 | result[leftIndex] = partials[leftIndex];
|
6771 | }
|
6772 | while (++argsIndex < holdersLength) {
|
6773 | result[holders[argsIndex]] = args[argsIndex];
|
6774 | }
|
6775 | while (argsLength--) {
|
6776 | result[leftIndex++] = args[argsIndex++];
|
6777 | }
|
6778 | return result;
|
6779 | }
|
6780 |
|
6781 | /**
|
6782 | * This function is like `composeArgs` except that the arguments composition
|
6783 | * is tailored for `_.partialRight`.
|
6784 | *
|
6785 | * @private
|
6786 | * @param {Array|Object} args The provided arguments.
|
6787 | * @param {Array} partials The arguments to append to those provided.
|
6788 | * @param {Array} holders The `partials` placeholder indexes.
|
6789 | * @returns {Array} Returns the new array of composed arguments.
|
6790 | */
|
6791 | function composeArgsRight(args, partials, holders) {
|
6792 | var holdersIndex = -1,
|
6793 | holdersLength = holders.length,
|
6794 | argsIndex = -1,
|
6795 | argsLength = nativeMax(args.length - holdersLength, 0),
|
6796 | rightIndex = -1,
|
6797 | rightLength = partials.length,
|
6798 | result = Array(argsLength + rightLength);
|
6799 |
|
6800 | while (++argsIndex < argsLength) {
|
6801 | result[argsIndex] = args[argsIndex];
|
6802 | }
|
6803 | var offset = argsIndex;
|
6804 | while (++rightIndex < rightLength) {
|
6805 | result[offset + rightIndex] = partials[rightIndex];
|
6806 | }
|
6807 | while (++holdersIndex < holdersLength) {
|
6808 | result[offset + holders[holdersIndex]] = args[argsIndex++];
|
6809 | }
|
6810 | return result;
|
6811 | }
|
6812 |
|
6813 | /**
|
6814 | * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function.
|
6815 | *
|
6816 | * @private
|
6817 | * @param {Function} setter The function to set keys and values of the accumulator object.
|
6818 | * @param {Function} [initializer] The function to initialize the accumulator object.
|
6819 | * @returns {Function} Returns the new aggregator function.
|
6820 | */
|
6821 | function createAggregator(setter, initializer) {
|
6822 | return function(collection, iteratee, thisArg) {
|
6823 | var result = initializer ? initializer() : {};
|
6824 | iteratee = getCallback(iteratee, thisArg, 3);
|
6825 |
|
6826 | if (isArray(collection)) {
|
6827 | var index = -1,
|
6828 | length = collection.length;
|
6829 |
|
6830 | while (++index < length) {
|
6831 | var value = collection[index];
|
6832 | setter(result, value, iteratee(value, index, collection), collection);
|
6833 | }
|
6834 | } else {
|
6835 | baseEach(collection, function(value, key, collection) {
|
6836 | setter(result, value, iteratee(value, key, collection), collection);
|
6837 | });
|
6838 | }
|
6839 | return result;
|
6840 | };
|
6841 | }
|
6842 |
|
6843 | /**
|
6844 | * Creates a `_.assign`, `_.defaults`, or `_.merge` function.
|
6845 | *
|
6846 | * @private
|
6847 | * @param {Function} assigner The function to assign values.
|
6848 | * @returns {Function} Returns the new assigner function.
|
6849 | */
|
6850 | function createAssigner(assigner) {
|
6851 | return restParam(function(object, sources) {
|
6852 | var index = -1,
|
6853 | length = object == null ? 0 : sources.length,
|
6854 | customizer = length > 2 ? sources[length - 2] : undefined,
|
6855 | guard = length > 2 ? sources[2] : undefined,
|
6856 | thisArg = length > 1 ? sources[length - 1] : undefined;
|
6857 |
|
6858 | if (typeof customizer == 'function') {
|
6859 | customizer = bindCallback(customizer, thisArg, 5);
|
6860 | length -= 2;
|
6861 | } else {
|
6862 | customizer = typeof thisArg == 'function' ? thisArg : undefined;
|
6863 | length -= (customizer ? 1 : 0);
|
6864 | }
|
6865 | if (guard && isIterateeCall(sources[0], sources[1], guard)) {
|
6866 | customizer = length < 3 ? undefined : customizer;
|
6867 | length = 1;
|
6868 | }
|
6869 | while (++index < length) {
|
6870 | var source = sources[index];
|
6871 | if (source) {
|
6872 | assigner(object, source, customizer);
|
6873 | }
|
6874 | }
|
6875 | return object;
|
6876 | });
|
6877 | }
|
6878 |
|
6879 | /**
|
6880 | * Creates a `baseEach` or `baseEachRight` function.
|
6881 | *
|
6882 | * @private
|
6883 | * @param {Function} eachFunc The function to iterate over a collection.
|
6884 | * @param {boolean} [fromRight] Specify iterating from right to left.
|
6885 | * @returns {Function} Returns the new base function.
|
6886 | */
|
6887 | function createBaseEach(eachFunc, fromRight) {
|
6888 | return function(collection, iteratee) {
|
6889 | var length = collection ? getLength(collection) : 0;
|
6890 | if (!isLength(length)) {
|
6891 | return eachFunc(collection, iteratee);
|
6892 | }
|
6893 | var index = fromRight ? length : -1,
|
6894 | iterable = toObject(collection);
|
6895 |
|
6896 | while ((fromRight ? index-- : ++index < length)) {
|
6897 | if (iteratee(iterable[index], index, iterable) === false) {
|
6898 | break;
|
6899 | }
|
6900 | }
|
6901 | return collection;
|
6902 | };
|
6903 | }
|
6904 |
|
6905 | /**
|
6906 | * Creates a base function for `_.forIn` or `_.forInRight`.
|
6907 | *
|
6908 | * @private
|
6909 | * @param {boolean} [fromRight] Specify iterating from right to left.
|
6910 | * @returns {Function} Returns the new base function.
|
6911 | */
|
6912 | function createBaseFor(fromRight) {
|
6913 | return function(object, iteratee, keysFunc) {
|
6914 | var iterable = toObject(object),
|
6915 | props = keysFunc(object),
|
6916 | length = props.length,
|
6917 | index = fromRight ? length : -1;
|
6918 |
|
6919 | while ((fromRight ? index-- : ++index < length)) {
|
6920 | var key = props[index];
|
6921 | if (iteratee(iterable[key], key, iterable) === false) {
|
6922 | break;
|
6923 | }
|
6924 | }
|
6925 | return object;
|
6926 | };
|
6927 | }
|
6928 |
|
6929 | /**
|
6930 | * Creates a function that wraps `func` and invokes it with the `this`
|
6931 | * binding of `thisArg`.
|
6932 | *
|
6933 | * @private
|
6934 | * @param {Function} func The function to bind.
|
6935 | * @param {*} [thisArg] The `this` binding of `func`.
|
6936 | * @returns {Function} Returns the new bound function.
|
6937 | */
|
6938 | function createBindWrapper(func, thisArg) {
|
6939 | var Ctor = createCtorWrapper(func);
|
6940 |
|
6941 | function wrapper() {
|
6942 | var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
|
6943 | return fn.apply(thisArg, arguments);
|
6944 | }
|
6945 | return wrapper;
|
6946 | }
|
6947 |
|
6948 | /**
|
6949 | * Creates a `Set` cache object to optimize linear searches of large arrays.
|
6950 | *
|
6951 | * @private
|
6952 | * @param {Array} [values] The values to cache.
|
6953 | * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
|
6954 | */
|
6955 | function createCache(values) {
|
6956 | return (nativeCreate && Set) ? new SetCache(values) : null;
|
6957 | }
|
6958 |
|
6959 | /**
|
6960 | * Creates a function that produces compound words out of the words in a
|
6961 | * given string.
|
6962 | *
|
6963 | * @private
|
6964 | * @param {Function} callback The function to combine each word.
|
6965 | * @returns {Function} Returns the new compounder function.
|
6966 | */
|
6967 | function createCompounder(callback) {
|
6968 | return function(string) {
|
6969 | var index = -1,
|
6970 | array = words(deburr(string)),
|
6971 | length = array.length,
|
6972 | result = '';
|
6973 |
|
6974 | while (++index < length) {
|
6975 | result = callback(result, array[index], index);
|
6976 | }
|
6977 | return result;
|
6978 | };
|
6979 | }
|
6980 |
|
6981 | /**
|
6982 | * Creates a function that produces an instance of `Ctor` regardless of
|
6983 | * whether it was invoked as part of a `new` expression or by `call` or `apply`.
|
6984 | *
|
6985 | * @private
|
6986 | * @param {Function} Ctor The constructor to wrap.
|
6987 | * @returns {Function} Returns the new wrapped function.
|
6988 | */
|
6989 | function createCtorWrapper(Ctor) {
|
6990 | return function() {
|
6991 | // Use a `switch` statement to work with class constructors.
|
6992 | // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
|
6993 | // for more details.
|
6994 | var args = arguments;
|
6995 | switch (args.length) {
|
6996 | case 0: return new Ctor;
|
6997 | case 1: return new Ctor(args[0]);
|
6998 | case 2: return new Ctor(args[0], args[1]);
|
6999 | case 3: return new Ctor(args[0], args[1], args[2]);
|
7000 | case 4: return new Ctor(args[0], args[1], args[2], args[3]);
|
7001 | case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
|
7002 | case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
|
7003 | case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
|
7004 | }
|
7005 | var thisBinding = baseCreate(Ctor.prototype),
|
7006 | result = Ctor.apply(thisBinding, args);
|
7007 |
|
7008 | // Mimic the constructor's `return` behavior.
|
7009 | // See https://es5.github.io/#x13.2.2 for more details.
|
7010 | return isObject(result) ? result : thisBinding;
|
7011 | };
|
7012 | }
|
7013 |
|
7014 | /**
|
7015 | * Creates a `_.curry` or `_.curryRight` function.
|
7016 | *
|
7017 | * @private
|
7018 | * @param {boolean} flag The curry bit flag.
|
7019 | * @returns {Function} Returns the new curry function.
|
7020 | */
|
7021 | function createCurry(flag) {
|
7022 | function curryFunc(func, arity, guard) {
|
7023 | if (guard && isIterateeCall(func, arity, guard)) {
|
7024 | arity = undefined;
|
7025 | }
|
7026 | var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity);
|
7027 | result.placeholder = curryFunc.placeholder;
|
7028 | return result;
|
7029 | }
|
7030 | return curryFunc;
|
7031 | }
|
7032 |
|
7033 | /**
|
7034 | * Creates a `_.defaults` or `_.defaultsDeep` function.
|
7035 | *
|
7036 | * @private
|
7037 | * @param {Function} assigner The function to assign values.
|
7038 | * @param {Function} customizer The function to customize assigned values.
|
7039 | * @returns {Function} Returns the new defaults function.
|
7040 | */
|
7041 | function createDefaults(assigner, customizer) {
|
7042 | return restParam(function(args) {
|
7043 | var object = args[0];
|
7044 | if (object == null) {
|
7045 | return object;
|
7046 | }
|
7047 | args.push(customizer);
|
7048 | return assigner.apply(undefined, args);
|
7049 | });
|
7050 | }
|
7051 |
|
7052 | /**
|
7053 | * Creates a `_.max` or `_.min` function.
|
7054 | *
|
7055 | * @private
|
7056 | * @param {Function} comparator The function used to compare values.
|
7057 | * @param {*} exValue The initial extremum value.
|
7058 | * @returns {Function} Returns the new extremum function.
|
7059 | */
|
7060 | function createExtremum(comparator, exValue) {
|
7061 | return function(collection, iteratee, thisArg) {
|
7062 | if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
|
7063 | iteratee = undefined;
|
7064 | }
|
7065 | iteratee = getCallback(iteratee, thisArg, 3);
|
7066 | if (iteratee.length == 1) {
|
7067 | collection = isArray(collection) ? collection : toIterable(collection);
|
7068 | var result = arrayExtremum(collection, iteratee, comparator, exValue);
|
7069 | if (!(collection.length && result === exValue)) {
|
7070 | return result;
|
7071 | }
|
7072 | }
|
7073 | return baseExtremum(collection, iteratee, comparator, exValue);
|
7074 | };
|
7075 | }
|
7076 |
|
7077 | /**
|
7078 | * Creates a `_.find` or `_.findLast` function.
|
7079 | *
|
7080 | * @private
|
7081 | * @param {Function} eachFunc The function to iterate over a collection.
|
7082 | * @param {boolean} [fromRight] Specify iterating from right to left.
|
7083 | * @returns {Function} Returns the new find function.
|
7084 | */
|
7085 | function createFind(eachFunc, fromRight) {
|
7086 | return function(collection, predicate, thisArg) {
|
7087 | predicate = getCallback(predicate, thisArg, 3);
|
7088 | if (isArray(collection)) {
|
7089 | var index = baseFindIndex(collection, predicate, fromRight);
|
7090 | return index > -1 ? collection[index] : undefined;
|
7091 | }
|
7092 | return baseFind(collection, predicate, eachFunc);
|
7093 | };
|
7094 | }
|
7095 |
|
7096 | /**
|
7097 | * Creates a `_.findIndex` or `_.findLastIndex` function.
|
7098 | *
|
7099 | * @private
|
7100 | * @param {boolean} [fromRight] Specify iterating from right to left.
|
7101 | * @returns {Function} Returns the new find function.
|
7102 | */
|
7103 | function createFindIndex(fromRight) {
|
7104 | return function(array, predicate, thisArg) {
|
7105 | if (!(array && array.length)) {
|
7106 | return -1;
|
7107 | }
|
7108 | predicate = getCallback(predicate, thisArg, 3);
|
7109 | return baseFindIndex(array, predicate, fromRight);
|
7110 | };
|
7111 | }
|
7112 |
|
7113 | /**
|
7114 | * Creates a `_.findKey` or `_.findLastKey` function.
|
7115 | *
|
7116 | * @private
|
7117 | * @param {Function} objectFunc The function to iterate over an object.
|
7118 | * @returns {Function} Returns the new find function.
|
7119 | */
|
7120 | function createFindKey(objectFunc) {
|
7121 | return function(object, predicate, thisArg) {
|
7122 | predicate = getCallback(predicate, thisArg, 3);
|
7123 | return baseFind(object, predicate, objectFunc, true);
|
7124 | };
|
7125 | }
|
7126 |
|
7127 | /**
|
7128 | * Creates a `_.flow` or `_.flowRight` function.
|
7129 | *
|
7130 | * @private
|
7131 | * @param {boolean} [fromRight] Specify iterating from right to left.
|
7132 | * @returns {Function} Returns the new flow function.
|
7133 | */
|
7134 | function createFlow(fromRight) {
|
7135 | return function() {
|
7136 | var wrapper,
|
7137 | length = arguments.length,
|
7138 | index = fromRight ? length : -1,
|
7139 | leftIndex = 0,
|
7140 | funcs = Array(length);
|
7141 |
|
7142 | while ((fromRight ? index-- : ++index < length)) {
|
7143 | var func = funcs[leftIndex++] = arguments[index];
|
7144 | if (typeof func != 'function') {
|
7145 | throw new TypeError(FUNC_ERROR_TEXT);
|
7146 | }
|
7147 | if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') {
|
7148 | wrapper = new LodashWrapper([], true);
|
7149 | }
|
7150 | }
|
7151 | index = wrapper ? -1 : length;
|
7152 | while (++index < length) {
|
7153 | func = funcs[index];
|
7154 |
|
7155 | var funcName = getFuncName(func),
|
7156 | data = funcName == 'wrapper' ? getData(func) : undefined;
|
7157 |
|
7158 | if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
|
7159 | wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
|
7160 | } else {
|
7161 | wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
|
7162 | }
|
7163 | }
|
7164 | return function() {
|
7165 | var args = arguments,
|
7166 | value = args[0];
|
7167 |
|
7168 | if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
|
7169 | return wrapper.plant(value).value();
|
7170 | }
|
7171 | var index = 0,
|
7172 | result = length ? funcs[index].apply(this, args) : value;
|
7173 |
|
7174 | while (++index < length) {
|
7175 | result = funcs[index].call(this, result);
|
7176 | }
|
7177 | return result;
|
7178 | };
|
7179 | };
|
7180 | }
|
7181 |
|
7182 | /**
|
7183 | * Creates a function for `_.forEach` or `_.forEachRight`.
|
7184 | *
|
7185 | * @private
|
7186 | * @param {Function} arrayFunc The function to iterate over an array.
|
7187 | * @param {Function} eachFunc The function to iterate over a collection.
|
7188 | * @returns {Function} Returns the new each function.
|
7189 | */
|
7190 | function createForEach(arrayFunc, eachFunc) {
|
7191 | return function(collection, iteratee, thisArg) {
|
7192 | return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
|
7193 | ? arrayFunc(collection, iteratee)
|
7194 | : eachFunc(collection, bindCallback(iteratee, thisArg, 3));
|
7195 | };
|
7196 | }
|
7197 |
|
7198 | /**
|
7199 | * Creates a function for `_.forIn` or `_.forInRight`.
|
7200 | *
|
7201 | * @private
|
7202 | * @param {Function} objectFunc The function to iterate over an object.
|
7203 | * @returns {Function} Returns the new each function.
|
7204 | */
|
7205 | function createForIn(objectFunc) {
|
7206 | return function(object, iteratee, thisArg) {
|
7207 | if (typeof iteratee != 'function' || thisArg !== undefined) {
|
7208 | iteratee = bindCallback(iteratee, thisArg, 3);
|
7209 | }
|
7210 | return objectFunc(object, iteratee, keysIn);
|
7211 | };
|
7212 | }
|
7213 |
|
7214 | /**
|
7215 | * Creates a function for `_.forOwn` or `_.forOwnRight`.
|
7216 | *
|
7217 | * @private
|
7218 | * @param {Function} objectFunc The function to iterate over an object.
|
7219 | * @returns {Function} Returns the new each function.
|
7220 | */
|
7221 | function createForOwn(objectFunc) {
|
7222 | return function(object, iteratee, thisArg) {
|
7223 | if (typeof iteratee != 'function' || thisArg !== undefined) {
|
7224 | iteratee = bindCallback(iteratee, thisArg, 3);
|
7225 | }
|
7226 | return objectFunc(object, iteratee);
|
7227 | };
|
7228 | }
|
7229 |
|
7230 | /**
|
7231 | * Creates a function for `_.mapKeys` or `_.mapValues`.
|
7232 | *
|
7233 | * @private
|
7234 | * @param {boolean} [isMapKeys] Specify mapping keys instead of values.
|
7235 | * @returns {Function} Returns the new map function.
|
7236 | */
|
7237 | function createObjectMapper(isMapKeys) {
|
7238 | return function(object, iteratee, thisArg) {
|
7239 | var result = {};
|
7240 | iteratee = getCallback(iteratee, thisArg, 3);
|
7241 |
|
7242 | baseForOwn(object, function(value, key, object) {
|
7243 | var mapped = iteratee(value, key, object);
|
7244 | key = isMapKeys ? mapped : key;
|
7245 | value = isMapKeys ? value : mapped;
|
7246 | result[key] = value;
|
7247 | });
|
7248 | return result;
|
7249 | };
|
7250 | }
|
7251 |
|
7252 | /**
|
7253 | * Creates a function for `_.padLeft` or `_.padRight`.
|
7254 | *
|
7255 | * @private
|
7256 | * @param {boolean} [fromRight] Specify padding from the right.
|
7257 | * @returns {Function} Returns the new pad function.
|
7258 | */
|
7259 | function createPadDir(fromRight) {
|
7260 | return function(string, length, chars) {
|
7261 | string = baseToString(string);
|
7262 | return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string);
|
7263 | };
|
7264 | }
|
7265 |
|
7266 | /**
|
7267 | * Creates a `_.partial` or `_.partialRight` function.
|
7268 | *
|
7269 | * @private
|
7270 | * @param {boolean} flag The partial bit flag.
|
7271 | * @returns {Function} Returns the new partial function.
|
7272 | */
|
7273 | function createPartial(flag) {
|
7274 | var partialFunc = restParam(function(func, partials) {
|
7275 | var holders = replaceHolders(partials, partialFunc.placeholder);
|
7276 | return createWrapper(func, flag, undefined, partials, holders);
|
7277 | });
|
7278 | return partialFunc;
|
7279 | }
|
7280 |
|
7281 | /**
|
7282 | * Creates a function for `_.reduce` or `_.reduceRight`.
|
7283 | *
|
7284 | * @private
|
7285 | * @param {Function} arrayFunc The function to iterate over an array.
|
7286 | * @param {Function} eachFunc The function to iterate over a collection.
|
7287 | * @returns {Function} Returns the new each function.
|
7288 | */
|
7289 | function createReduce(arrayFunc, eachFunc) {
|
7290 | return function(collection, iteratee, accumulator, thisArg) {
|
7291 | var initFromArray = arguments.length < 3;
|
7292 | return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
|
7293 | ? arrayFunc(collection, iteratee, accumulator, initFromArray)
|
7294 | : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
|
7295 | };
|
7296 | }
|
7297 |
|
7298 | /**
|
7299 | * Creates a function that wraps `func` and invokes it with optional `this`
|
7300 | * binding of, partial application, and currying.
|
7301 | *
|
7302 | * @private
|
7303 | * @param {Function|string} func The function or method name to reference.
|
7304 | * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
|
7305 | * @param {*} [thisArg] The `this` binding of `func`.
|
7306 | * @param {Array} [partials] The arguments to prepend to those provided to the new function.
|
7307 | * @param {Array} [holders] The `partials` placeholder indexes.
|
7308 | * @param {Array} [partialsRight] The arguments to append to those provided to the new function.
|
7309 | * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
|
7310 | * @param {Array} [argPos] The argument positions of the new function.
|
7311 | * @param {number} [ary] The arity cap of `func`.
|
7312 | * @param {number} [arity] The arity of `func`.
|
7313 | * @returns {Function} Returns the new wrapped function.
|
7314 | */
|
7315 | function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
|
7316 | var isAry = bitmask & ARY_FLAG,
|
7317 | isBind = bitmask & BIND_FLAG,
|
7318 | isBindKey = bitmask & BIND_KEY_FLAG,
|
7319 | isCurry = bitmask & CURRY_FLAG,
|
7320 | isCurryBound = bitmask & CURRY_BOUND_FLAG,
|
7321 | isCurryRight = bitmask & CURRY_RIGHT_FLAG,
|
7322 | Ctor = isBindKey ? undefined : createCtorWrapper(func);
|
7323 |
|
7324 | function wrapper() {
|
7325 | // Avoid `arguments` object use disqualifying optimizations by
|
7326 | // converting it to an array before providing it to other functions.
|
7327 | var length = arguments.length,
|
7328 | index = length,
|
7329 | args = Array(length);
|
7330 |
|
7331 | while (index--) {
|
7332 | args[index] = arguments[index];
|
7333 | }
|
7334 | if (partials) {
|
7335 | args = composeArgs(args, partials, holders);
|
7336 | }
|
7337 | if (partialsRight) {
|
7338 | args = composeArgsRight(args, partialsRight, holdersRight);
|
7339 | }
|
7340 | if (isCurry || isCurryRight) {
|
7341 | var placeholder = wrapper.placeholder,
|
7342 | argsHolders = replaceHolders(args, placeholder);
|
7343 |
|
7344 | length -= argsHolders.length;
|
7345 | if (length < arity) {
|
7346 | var newArgPos = argPos ? arrayCopy(argPos) : undefined,
|
7347 | newArity = nativeMax(arity - length, 0),
|
7348 | newsHolders = isCurry ? argsHolders : undefined,
|
7349 | newHoldersRight = isCurry ? undefined : argsHolders,
|
7350 | newPartials = isCurry ? args : undefined,
|
7351 | newPartialsRight = isCurry ? undefined : args;
|
7352 |
|
7353 | bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
|
7354 | bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
|
7355 |
|
7356 | if (!isCurryBound) {
|
7357 | bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
|
7358 | }
|
7359 | var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity],
|
7360 | result = createHybridWrapper.apply(undefined, newData);
|
7361 |
|
7362 | if (isLaziable(func)) {
|
7363 | setData(result, newData);
|
7364 | }
|
7365 | result.placeholder = placeholder;
|
7366 | return result;
|
7367 | }
|
7368 | }
|
7369 | var thisBinding = isBind ? thisArg : this,
|
7370 | fn = isBindKey ? thisBinding[func] : func;
|
7371 |
|
7372 | if (argPos) {
|
7373 | args = reorder(args, argPos);
|
7374 | }
|
7375 | if (isAry && ary < args.length) {
|
7376 | args.length = ary;
|
7377 | }
|
7378 | if (this && this !== root && this instanceof wrapper) {
|
7379 | fn = Ctor || createCtorWrapper(func);
|
7380 | }
|
7381 | return fn.apply(thisBinding, args);
|
7382 | }
|
7383 | return wrapper;
|
7384 | }
|
7385 |
|
7386 | /**
|
7387 | * Creates the padding required for `string` based on the given `length`.
|
7388 | * The `chars` string is truncated if the number of characters exceeds `length`.
|
7389 | *
|
7390 | * @private
|
7391 | * @param {string} string The string to create padding for.
|
7392 | * @param {number} [length=0] The padding length.
|
7393 | * @param {string} [chars=' '] The string used as padding.
|
7394 | * @returns {string} Returns the pad for `string`.
|
7395 | */
|
7396 | function createPadding(string, length, chars) {
|
7397 | var strLength = string.length;
|
7398 | length = +length;
|
7399 |
|
7400 | if (strLength >= length || !nativeIsFinite(length)) {
|
7401 | return '';
|
7402 | }
|
7403 | var padLength = length - strLength;
|
7404 | chars = chars == null ? ' ' : (chars + '');
|
7405 | return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength);
|
7406 | }
|
7407 |
|
7408 | /**
|
7409 | * Creates a function that wraps `func` and invokes it with the optional `this`
|
7410 | * binding of `thisArg` and the `partials` prepended to those provided to
|
7411 | * the wrapper.
|
7412 | *
|
7413 | * @private
|
7414 | * @param {Function} func The function to partially apply arguments to.
|
7415 | * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
|
7416 | * @param {*} thisArg The `this` binding of `func`.
|
7417 | * @param {Array} partials The arguments to prepend to those provided to the new function.
|
7418 | * @returns {Function} Returns the new bound function.
|
7419 | */
|
7420 | function createPartialWrapper(func, bitmask, thisArg, partials) {
|
7421 | var isBind = bitmask & BIND_FLAG,
|
7422 | Ctor = createCtorWrapper(func);
|
7423 |
|
7424 | function wrapper() {
|
7425 | // Avoid `arguments` object use disqualifying optimizations by
|
7426 | // converting it to an array before providing it `func`.
|
7427 | var argsIndex = -1,
|
7428 | argsLength = arguments.length,
|
7429 | leftIndex = -1,
|
7430 | leftLength = partials.length,
|
7431 | args = Array(leftLength + argsLength);
|
7432 |
|
7433 | while (++leftIndex < leftLength) {
|
7434 | args[leftIndex] = partials[leftIndex];
|
7435 | }
|
7436 | while (argsLength--) {
|
7437 | args[leftIndex++] = arguments[++argsIndex];
|
7438 | }
|
7439 | var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
|
7440 | return fn.apply(isBind ? thisArg : this, args);
|
7441 | }
|
7442 | return wrapper;
|
7443 | }
|
7444 |
|
7445 | /**
|
7446 | * Creates a `_.ceil`, `_.floor`, or `_.round` function.
|
7447 | *
|
7448 | * @private
|
7449 | * @param {string} methodName The name of the `Math` method to use when rounding.
|
7450 | * @returns {Function} Returns the new round function.
|
7451 | */
|
7452 | function createRound(methodName) {
|
7453 | var func = Math[methodName];
|
7454 | return function(number, precision) {
|
7455 | precision = precision === undefined ? 0 : (+precision || 0);
|
7456 | if (precision) {
|
7457 | precision = pow(10, precision);
|
7458 | return func(number * precision) / precision;
|
7459 | }
|
7460 | return func(number);
|
7461 | };
|
7462 | }
|
7463 |
|
7464 | /**
|
7465 | * Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
|
7466 | *
|
7467 | * @private
|
7468 | * @param {boolean} [retHighest] Specify returning the highest qualified index.
|
7469 | * @returns {Function} Returns the new index function.
|
7470 | */
|
7471 | function createSortedIndex(retHighest) {
|
7472 | return function(array, value, iteratee, thisArg) {
|
7473 | var callback = getCallback(iteratee);
|
7474 | return (iteratee == null && callback === baseCallback)
|
7475 | ? binaryIndex(array, value, retHighest)
|
7476 | : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest);
|
7477 | };
|
7478 | }
|
7479 |
|
7480 | /**
|
7481 | * Creates a function that either curries or invokes `func` with optional
|
7482 | * `this` binding and partially applied arguments.
|
7483 | *
|
7484 | * @private
|
7485 | * @param {Function|string} func The function or method name to reference.
|
7486 | * @param {number} bitmask The bitmask of flags.
|
7487 | * The bitmask may be composed of the following flags:
|
7488 | * 1 - `_.bind`
|
7489 | * 2 - `_.bindKey`
|
7490 | * 4 - `_.curry` or `_.curryRight` of a bound function
|
7491 | * 8 - `_.curry`
|
7492 | * 16 - `_.curryRight`
|
7493 | * 32 - `_.partial`
|
7494 | * 64 - `_.partialRight`
|
7495 | * 128 - `_.rearg`
|
7496 | * 256 - `_.ary`
|
7497 | * @param {*} [thisArg] The `this` binding of `func`.
|
7498 | * @param {Array} [partials] The arguments to be partially applied.
|
7499 | * @param {Array} [holders] The `partials` placeholder indexes.
|
7500 | * @param {Array} [argPos] The argument positions of the new function.
|
7501 | * @param {number} [ary] The arity cap of `func`.
|
7502 | * @param {number} [arity] The arity of `func`.
|
7503 | * @returns {Function} Returns the new wrapped function.
|
7504 | */
|
7505 | function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
|
7506 | var isBindKey = bitmask & BIND_KEY_FLAG;
|
7507 | if (!isBindKey && typeof func != 'function') {
|
7508 | throw new TypeError(FUNC_ERROR_TEXT);
|
7509 | }
|
7510 | var length = partials ? partials.length : 0;
|
7511 | if (!length) {
|
7512 | bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
|
7513 | partials = holders = undefined;
|
7514 | }
|
7515 | length -= (holders ? holders.length : 0);
|
7516 | if (bitmask & PARTIAL_RIGHT_FLAG) {
|
7517 | var partialsRight = partials,
|
7518 | holdersRight = holders;
|
7519 |
|
7520 | partials = holders = undefined;
|
7521 | }
|
7522 | var data = isBindKey ? undefined : getData(func),
|
7523 | newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
|
7524 |
|
7525 | if (data) {
|
7526 | mergeData(newData, data);
|
7527 | bitmask = newData[1];
|
7528 | arity = newData[9];
|
7529 | }
|
7530 | newData[9] = arity == null
|
7531 | ? (isBindKey ? 0 : func.length)
|
7532 | : (nativeMax(arity - length, 0) || 0);
|
7533 |
|
7534 | if (bitmask == BIND_FLAG) {
|
7535 | var result = createBindWrapper(newData[0], newData[2]);
|
7536 | } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
|
7537 | result = createPartialWrapper.apply(undefined, newData);
|
7538 | } else {
|
7539 | result = createHybridWrapper.apply(undefined, newData);
|
7540 | }
|
7541 | var setter = data ? baseSetData : setData;
|
7542 | return setter(result, newData);
|
7543 | }
|
7544 |
|
7545 | /**
|
7546 | * A specialized version of `baseIsEqualDeep` for arrays with support for
|
7547 | * partial deep comparisons.
|
7548 | *
|
7549 | * @private
|
7550 | * @param {Array} array The array to compare.
|
7551 | * @param {Array} other The other array to compare.
|
7552 | * @param {Function} equalFunc The function to determine equivalents of values.
|
7553 | * @param {Function} [customizer] The function to customize comparing arrays.
|
7554 | * @param {boolean} [isLoose] Specify performing partial comparisons.
|
7555 | * @param {Array} [stackA] Tracks traversed `value` objects.
|
7556 | * @param {Array} [stackB] Tracks traversed `other` objects.
|
7557 | * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
|
7558 | */
|
7559 | function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
|
7560 | var index = -1,
|
7561 | arrLength = array.length,
|
7562 | othLength = other.length;
|
7563 |
|
7564 | if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
|
7565 | return false;
|
7566 | }
|
7567 | // Ignore non-index properties.
|
7568 | while (++index < arrLength) {
|
7569 | var arrValue = array[index],
|
7570 | othValue = other[index],
|
7571 | result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
|
7572 |
|
7573 | if (result !== undefined) {
|
7574 | if (result) {
|
7575 | continue;
|
7576 | }
|
7577 | return false;
|
7578 | }
|
7579 | // Recursively compare arrays (susceptible to call stack limits).
|
7580 | if (isLoose) {
|
7581 | if (!arraySome(other, function(othValue) {
|
7582 | return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
|
7583 | })) {
|
7584 | return false;
|
7585 | }
|
7586 | } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
|
7587 | return false;
|
7588 | }
|
7589 | }
|
7590 | return true;
|
7591 | }
|
7592 |
|
7593 | /**
|
7594 | * A specialized version of `baseIsEqualDeep` for comparing objects of
|
7595 | * the same `toStringTag`.
|
7596 | *
|
7597 | * **Note:** This function only supports comparing values with tags of
|
7598 | * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
|
7599 | *
|
7600 | * @private
|
7601 | * @param {Object} object The object to compare.
|
7602 | * @param {Object} other The other object to compare.
|
7603 | * @param {string} tag The `toStringTag` of the objects to compare.
|
7604 | * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
|
7605 | */
|
7606 | function equalByTag(object, other, tag) {
|
7607 | switch (tag) {
|
7608 | case boolTag:
|
7609 | case dateTag:
|
7610 | // Coerce dates and booleans to numbers, dates to milliseconds and booleans
|
7611 | // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
|
7612 | return +object == +other;
|
7613 |
|
7614 | case errorTag:
|
7615 | return object.name == other.name && object.message == other.message;
|
7616 |
|
7617 | case numberTag:
|
7618 | // Treat `NaN` vs. `NaN` as equal.
|
7619 | return (object != +object)
|
7620 | ? other != +other
|
7621 | : object == +other;
|
7622 |
|
7623 | case regexpTag:
|
7624 | case stringTag:
|
7625 | // Coerce regexes to strings and treat strings primitives and string
|
7626 | // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
|
7627 | return object == (other + '');
|
7628 | }
|
7629 | return false;
|
7630 | }
|
7631 |
|
7632 | /**
|
7633 | * A specialized version of `baseIsEqualDeep` for objects with support for
|
7634 | * partial deep comparisons.
|
7635 | *
|
7636 | * @private
|
7637 | * @param {Object} object The object to compare.
|
7638 | * @param {Object} other The other object to compare.
|
7639 | * @param {Function} equalFunc The function to determine equivalents of values.
|
7640 | * @param {Function} [customizer] The function to customize comparing values.
|
7641 | * @param {boolean} [isLoose] Specify performing partial comparisons.
|
7642 | * @param {Array} [stackA] Tracks traversed `value` objects.
|
7643 | * @param {Array} [stackB] Tracks traversed `other` objects.
|
7644 | * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
|
7645 | */
|
7646 | function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
|
7647 | var objProps = keys(object),
|
7648 | objLength = objProps.length,
|
7649 | othProps = keys(other),
|
7650 | othLength = othProps.length;
|
7651 |
|
7652 | if (objLength != othLength && !isLoose) {
|
7653 | return false;
|
7654 | }
|
7655 | var index = objLength;
|
7656 | while (index--) {
|
7657 | var key = objProps[index];
|
7658 | if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
|
7659 | return false;
|
7660 | }
|
7661 | }
|
7662 | var skipCtor = isLoose;
|
7663 | while (++index < objLength) {
|
7664 | key = objProps[index];
|
7665 | var objValue = object[key],
|
7666 | othValue = other[key],
|
7667 | result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
|
7668 |
|
7669 | // Recursively compare objects (susceptible to call stack limits).
|
7670 | if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
|
7671 | return false;
|
7672 | }
|
7673 | skipCtor || (skipCtor = key == 'constructor');
|
7674 | }
|
7675 | if (!skipCtor) {
|
7676 | var objCtor = object.constructor,
|
7677 | othCtor = other.constructor;
|
7678 |
|
7679 | // Non `Object` object instances with different constructors are not equal.
|
7680 | if (objCtor != othCtor &&
|
7681 | ('constructor' in object && 'constructor' in other) &&
|
7682 | !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
|
7683 | typeof othCtor == 'function' && othCtor instanceof othCtor)) {
|
7684 | return false;
|
7685 | }
|
7686 | }
|
7687 | return true;
|
7688 | }
|
7689 |
|
7690 | /**
|
7691 | * Gets the appropriate "callback" function. If the `_.callback` method is
|
7692 | * customized this function returns the custom method, otherwise it returns
|
7693 | * the `baseCallback` function. If arguments are provided the chosen function
|
7694 | * is invoked with them and its result is returned.
|
7695 | *
|
7696 | * @private
|
7697 | * @returns {Function} Returns the chosen function or its result.
|
7698 | */
|
7699 | function getCallback(func, thisArg, argCount) {
|
7700 | var result = lodash.callback || callback;
|
7701 | result = result === callback ? baseCallback : result;
|
7702 | return argCount ? result(func, thisArg, argCount) : result;
|
7703 | }
|
7704 |
|
7705 | /**
|
7706 | * Gets metadata for `func`.
|
7707 | *
|
7708 | * @private
|
7709 | * @param {Function} func The function to query.
|
7710 | * @returns {*} Returns the metadata for `func`.
|
7711 | */
|
7712 | var getData = !metaMap ? noop : function(func) {
|
7713 | return metaMap.get(func);
|
7714 | };
|
7715 |
|
7716 | /**
|
7717 | * Gets the name of `func`.
|
7718 | *
|
7719 | * @private
|
7720 | * @param {Function} func The function to query.
|
7721 | * @returns {string} Returns the function name.
|
7722 | */
|
7723 | function getFuncName(func) {
|
7724 | var result = func.name,
|
7725 | array = realNames[result],
|
7726 | length = array ? array.length : 0;
|
7727 |
|
7728 | while (length--) {
|
7729 | var data = array[length],
|
7730 | otherFunc = data.func;
|
7731 | if (otherFunc == null || otherFunc == func) {
|
7732 | return data.name;
|
7733 | }
|
7734 | }
|
7735 | return result;
|
7736 | }
|
7737 |
|
7738 | /**
|
7739 | * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
|
7740 | * customized this function returns the custom method, otherwise it returns
|
7741 | * the `baseIndexOf` function. If arguments are provided the chosen function
|
7742 | * is invoked with them and its result is returned.
|
7743 | *
|
7744 | * @private
|
7745 | * @returns {Function|number} Returns the chosen function or its result.
|
7746 | */
|
7747 | function getIndexOf(collection, target, fromIndex) {
|
7748 | var result = lodash.indexOf || indexOf;
|
7749 | result = result === indexOf ? baseIndexOf : result;
|
7750 | return collection ? result(collection, target, fromIndex) : result;
|
7751 | }
|
7752 |
|
7753 | /**
|
7754 | * Gets the "length" property value of `object`.
|
7755 | *
|
7756 | * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
|
7757 | * that affects Safari on at least iOS 8.1-8.3 ARM64.
|
7758 | *
|
7759 | * @private
|
7760 | * @param {Object} object The object to query.
|
7761 | * @returns {*} Returns the "length" value.
|
7762 | */
|
7763 | var getLength = baseProperty('length');
|
7764 |
|
7765 | /**
|
7766 | * Gets the propery names, values, and compare flags of `object`.
|
7767 | *
|
7768 | * @private
|
7769 | * @param {Object} object The object to query.
|
7770 | * @returns {Array} Returns the match data of `object`.
|
7771 | */
|
7772 | function getMatchData(object) {
|
7773 | var result = pairs(object),
|
7774 | length = result.length;
|
7775 |
|
7776 | while (length--) {
|
7777 | result[length][2] = isStrictComparable(result[length][1]);
|
7778 | }
|
7779 | return result;
|
7780 | }
|
7781 |
|
7782 | /**
|
7783 | * Gets the native function at `key` of `object`.
|
7784 | *
|
7785 | * @private
|
7786 | * @param {Object} object The object to query.
|
7787 | * @param {string} key The key of the method to get.
|
7788 | * @returns {*} Returns the function if it's native, else `undefined`.
|
7789 | */
|
7790 | function getNative(object, key) {
|
7791 | var value = object == null ? undefined : object[key];
|
7792 | return isNative(value) ? value : undefined;
|
7793 | }
|
7794 |
|
7795 | /**
|
7796 | * Gets the view, applying any `transforms` to the `start` and `end` positions.
|
7797 | *
|
7798 | * @private
|
7799 | * @param {number} start The start of the view.
|
7800 | * @param {number} end The end of the view.
|
7801 | * @param {Array} transforms The transformations to apply to the view.
|
7802 | * @returns {Object} Returns an object containing the `start` and `end`
|
7803 | * positions of the view.
|
7804 | */
|
7805 | function getView(start, end, transforms) {
|
7806 | var index = -1,
|
7807 | length = transforms.length;
|
7808 |
|
7809 | while (++index < length) {
|
7810 | var data = transforms[index],
|
7811 | size = data.size;
|
7812 |
|
7813 | switch (data.type) {
|
7814 | case 'drop': start += size; break;
|
7815 | case 'dropRight': end -= size; break;
|
7816 | case 'take': end = nativeMin(end, start + size); break;
|
7817 | case 'takeRight': start = nativeMax(start, end - size); break;
|
7818 | }
|
7819 | }
|
7820 | return { 'start': start, 'end': end };
|
7821 | }
|
7822 |
|
7823 | /**
|
7824 | * Initializes an array clone.
|
7825 | *
|
7826 | * @private
|
7827 | * @param {Array} array The array to clone.
|
7828 | * @returns {Array} Returns the initialized clone.
|
7829 | */
|
7830 | function initCloneArray(array) {
|
7831 | var length = array.length,
|
7832 | result = new array.constructor(length);
|
7833 |
|
7834 | // Add array properties assigned by `RegExp#exec`.
|
7835 | if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
|
7836 | result.index = array.index;
|
7837 | result.input = array.input;
|
7838 | }
|
7839 | return result;
|
7840 | }
|
7841 |
|
7842 | /**
|
7843 | * Initializes an object clone.
|
7844 | *
|
7845 | * @private
|
7846 | * @param {Object} object The object to clone.
|
7847 | * @returns {Object} Returns the initialized clone.
|
7848 | */
|
7849 | function initCloneObject(object) {
|
7850 | var Ctor = object.constructor;
|
7851 | if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
|
7852 | Ctor = Object;
|
7853 | }
|
7854 | return new Ctor;
|
7855 | }
|
7856 |
|
7857 | /**
|
7858 | * Initializes an object clone based on its `toStringTag`.
|
7859 | *
|
7860 | * **Note:** This function only supports cloning values with tags of
|
7861 | * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
|
7862 | *
|
7863 | * @private
|
7864 | * @param {Object} object The object to clone.
|
7865 | * @param {string} tag The `toStringTag` of the object to clone.
|
7866 | * @param {boolean} [isDeep] Specify a deep clone.
|
7867 | * @returns {Object} Returns the initialized clone.
|
7868 | */
|
7869 | function initCloneByTag(object, tag, isDeep) {
|
7870 | var Ctor = object.constructor;
|
7871 | switch (tag) {
|
7872 | case arrayBufferTag:
|
7873 | return bufferClone(object);
|
7874 |
|
7875 | case boolTag:
|
7876 | case dateTag:
|
7877 | return new Ctor(+object);
|
7878 |
|
7879 | case float32Tag: case float64Tag:
|
7880 | case int8Tag: case int16Tag: case int32Tag:
|
7881 | case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
|
7882 | var buffer = object.buffer;
|
7883 | return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
|
7884 |
|
7885 | case numberTag:
|
7886 | case stringTag:
|
7887 | return new Ctor(object);
|
7888 |
|
7889 | case regexpTag:
|
7890 | var result = new Ctor(object.source, reFlags.exec(object));
|
7891 | result.lastIndex = object.lastIndex;
|
7892 | }
|
7893 | return result;
|
7894 | }
|
7895 |
|
7896 | /**
|
7897 | * Invokes the method at `path` on `object`.
|
7898 | *
|
7899 | * @private
|
7900 | * @param {Object} object The object to query.
|
7901 | * @param {Array|string} path The path of the method to invoke.
|
7902 | * @param {Array} args The arguments to invoke the method with.
|
7903 | * @returns {*} Returns the result of the invoked method.
|
7904 | */
|
7905 | function invokePath(object, path, args) {
|
7906 | if (object != null && !isKey(path, object)) {
|
7907 | path = toPath(path);
|
7908 | object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
|
7909 | path = last(path);
|
7910 | }
|
7911 | var func = object == null ? object : object[path];
|
7912 | return func == null ? undefined : func.apply(object, args);
|
7913 | }
|
7914 |
|
7915 | /**
|
7916 | * Checks if `value` is array-like.
|
7917 | *
|
7918 | * @private
|
7919 | * @param {*} value The value to check.
|
7920 | * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
|
7921 | */
|
7922 | function isArrayLike(value) {
|
7923 | return value != null && isLength(getLength(value));
|
7924 | }
|
7925 |
|
7926 | /**
|
7927 | * Checks if `value` is a valid array-like index.
|
7928 | *
|
7929 | * @private
|
7930 | * @param {*} value The value to check.
|
7931 | * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
|
7932 | * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
|
7933 | */
|
7934 | function isIndex(value, length) {
|
7935 | value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
|
7936 | length = length == null ? MAX_SAFE_INTEGER : length;
|
7937 | return value > -1 && value % 1 == 0 && value < length;
|
7938 | }
|
7939 |
|
7940 | /**
|
7941 | * Checks if the provided arguments are from an iteratee call.
|
7942 | *
|
7943 | * @private
|
7944 | * @param {*} value The potential iteratee value argument.
|
7945 | * @param {*} index The potential iteratee index or key argument.
|
7946 | * @param {*} object The potential iteratee object argument.
|
7947 | * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
|
7948 | */
|
7949 | function isIterateeCall(value, index, object) {
|
7950 | if (!isObject(object)) {
|
7951 | return false;
|
7952 | }
|
7953 | var type = typeof index;
|
7954 | if (type == 'number'
|
7955 | ? (isArrayLike(object) && isIndex(index, object.length))
|
7956 | : (type == 'string' && index in object)) {
|
7957 | var other = object[index];
|
7958 | return value === value ? (value === other) : (other !== other);
|
7959 | }
|
7960 | return false;
|
7961 | }
|
7962 |
|
7963 | /**
|
7964 | * Checks if `value` is a property name and not a property path.
|
7965 | *
|
7966 | * @private
|
7967 | * @param {*} value The value to check.
|
7968 | * @param {Object} [object] The object to query keys on.
|
7969 | * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
|
7970 | */
|
7971 | function isKey(value, object) {
|
7972 | var type = typeof value;
|
7973 | if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
|
7974 | return true;
|
7975 | }
|
7976 | if (isArray(value)) {
|
7977 | return false;
|
7978 | }
|
7979 | var result = !reIsDeepProp.test(value);
|
7980 | return result || (object != null && value in toObject(object));
|
7981 | }
|
7982 |
|
7983 | /**
|
7984 | * Checks if `func` has a lazy counterpart.
|
7985 | *
|
7986 | * @private
|
7987 | * @param {Function} func The function to check.
|
7988 | * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
|
7989 | */
|
7990 | function isLaziable(func) {
|
7991 | var funcName = getFuncName(func);
|
7992 | if (!(funcName in LazyWrapper.prototype)) {
|
7993 | return false;
|
7994 | }
|
7995 | var other = lodash[funcName];
|
7996 | if (func === other) {
|
7997 | return true;
|
7998 | }
|
7999 | var data = getData(other);
|
8000 | return !!data && func === data[0];
|
8001 | }
|
8002 |
|
8003 | /**
|
8004 | * Checks if `value` is a valid array-like length.
|
8005 | *
|
8006 | * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
|
8007 | *
|
8008 | * @private
|
8009 | * @param {*} value The value to check.
|
8010 | * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
|
8011 | */
|
8012 | function isLength(value) {
|
8013 | return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
|
8014 | }
|
8015 |
|
8016 | /**
|
8017 | * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
|
8018 | *
|
8019 | * @private
|
8020 | * @param {*} value The value to check.
|
8021 | * @returns {boolean} Returns `true` if `value` if suitable for strict
|
8022 | * equality comparisons, else `false`.
|
8023 | */
|
8024 | function isStrictComparable(value) {
|
8025 | return value === value && !isObject(value);
|
8026 | }
|
8027 |
|
8028 | /**
|
8029 | * Merges the function metadata of `source` into `data`.
|
8030 | *
|
8031 | * Merging metadata reduces the number of wrappers required to invoke a function.
|
8032 | * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
|
8033 | * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
|
8034 | * augment function arguments, making the order in which they are executed important,
|
8035 | * preventing the merging of metadata. However, we make an exception for a safe
|
8036 | * common case where curried functions have `_.ary` and or `_.rearg` applied.
|
8037 | *
|
8038 | * @private
|
8039 | * @param {Array} data The destination metadata.
|
8040 | * @param {Array} source The source metadata.
|
8041 | * @returns {Array} Returns `data`.
|
8042 | */
|
8043 | function mergeData(data, source) {
|
8044 | var bitmask = data[1],
|
8045 | srcBitmask = source[1],
|
8046 | newBitmask = bitmask | srcBitmask,
|
8047 | isCommon = newBitmask < ARY_FLAG;
|
8048 |
|
8049 | var isCombo =
|
8050 | (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) ||
|
8051 | (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) ||
|
8052 | (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG);
|
8053 |
|
8054 | // Exit early if metadata can't be merged.
|
8055 | if (!(isCommon || isCombo)) {
|
8056 | return data;
|
8057 | }
|
8058 | // Use source `thisArg` if available.
|
8059 | if (srcBitmask & BIND_FLAG) {
|
8060 | data[2] = source[2];
|
8061 | // Set when currying a bound function.
|
8062 | newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
|
8063 | }
|
8064 | // Compose partial arguments.
|
8065 | var value = source[3];
|
8066 | if (value) {
|
8067 | var partials = data[3];
|
8068 | data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
|
8069 | data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
|
8070 | }
|
8071 | // Compose partial right arguments.
|
8072 | value = source[5];
|
8073 | if (value) {
|
8074 | partials = data[5];
|
8075 | data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
|
8076 | data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
|
8077 | }
|
8078 | // Use source `argPos` if available.
|
8079 | value = source[7];
|
8080 | if (value) {
|
8081 | data[7] = arrayCopy(value);
|
8082 | }
|
8083 | // Use source `ary` if it's smaller.
|
8084 | if (srcBitmask & ARY_FLAG) {
|
8085 | data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
|
8086 | }
|
8087 | // Use source `arity` if one is not provided.
|
8088 | if (data[9] == null) {
|
8089 | data[9] = source[9];
|
8090 | }
|
8091 | // Use source `func` and merge bitmasks.
|
8092 | data[0] = source[0];
|
8093 | data[1] = newBitmask;
|
8094 |
|
8095 | return data;
|
8096 | }
|
8097 |
|
8098 | /**
|
8099 | * Used by `_.defaultsDeep` to customize its `_.merge` use.
|
8100 | *
|
8101 | * @private
|
8102 | * @param {*} objectValue The destination object property value.
|
8103 | * @param {*} sourceValue The source object property value.
|
8104 | * @returns {*} Returns the value to assign to the destination object.
|
8105 | */
|
8106 | function mergeDefaults(objectValue, sourceValue) {
|
8107 | return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults);
|
8108 | }
|
8109 |
|
8110 | /**
|
8111 | * A specialized version of `_.pick` which picks `object` properties specified
|
8112 | * by `props`.
|
8113 | *
|
8114 | * @private
|
8115 | * @param {Object} object The source object.
|
8116 | * @param {string[]} props The property names to pick.
|
8117 | * @returns {Object} Returns the new object.
|
8118 | */
|
8119 | function pickByArray(object, props) {
|
8120 | object = toObject(object);
|
8121 |
|
8122 | var index = -1,
|
8123 | length = props.length,
|
8124 | result = {};
|
8125 |
|
8126 | while (++index < length) {
|
8127 | var key = props[index];
|
8128 | if (key in object) {
|
8129 | result[key] = object[key];
|
8130 | }
|
8131 | }
|
8132 | return result;
|
8133 | }
|
8134 |
|
8135 | /**
|
8136 | * A specialized version of `_.pick` which picks `object` properties `predicate`
|
8137 | * returns truthy for.
|
8138 | *
|
8139 | * @private
|
8140 | * @param {Object} object The source object.
|
8141 | * @param {Function} predicate The function invoked per iteration.
|
8142 | * @returns {Object} Returns the new object.
|
8143 | */
|
8144 | function pickByCallback(object, predicate) {
|
8145 | var result = {};
|
8146 | baseForIn(object, function(value, key, object) {
|
8147 | if (predicate(value, key, object)) {
|
8148 | result[key] = value;
|
8149 | }
|
8150 | });
|
8151 | return result;
|
8152 | }
|
8153 |
|
8154 | /**
|
8155 | * Reorder `array` according to the specified indexes where the element at
|
8156 | * the first index is assigned as the first element, the element at
|
8157 | * the second index is assigned as the second element, and so on.
|
8158 | *
|
8159 | * @private
|
8160 | * @param {Array} array The array to reorder.
|
8161 | * @param {Array} indexes The arranged array indexes.
|
8162 | * @returns {Array} Returns `array`.
|
8163 | */
|
8164 | function reorder(array, indexes) {
|
8165 | var arrLength = array.length,
|
8166 | length = nativeMin(indexes.length, arrLength),
|
8167 | oldArray = arrayCopy(array);
|
8168 |
|
8169 | while (length--) {
|
8170 | var index = indexes[length];
|
8171 | array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
|
8172 | }
|
8173 | return array;
|
8174 | }
|
8175 |
|
8176 | /**
|
8177 | * Sets metadata for `func`.
|
8178 | *
|
8179 | * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
|
8180 | * period of time, it will trip its breaker and transition to an identity function
|
8181 | * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
|
8182 | * for more details.
|
8183 | *
|
8184 | * @private
|
8185 | * @param {Function} func The function to associate metadata with.
|
8186 | * @param {*} data The metadata.
|
8187 | * @returns {Function} Returns `func`.
|
8188 | */
|
8189 | var setData = (function() {
|
8190 | var count = 0,
|
8191 | lastCalled = 0;
|
8192 |
|
8193 | return function(key, value) {
|
8194 | var stamp = now(),
|
8195 | remaining = HOT_SPAN - (stamp - lastCalled);
|
8196 |
|
8197 | lastCalled = stamp;
|
8198 | if (remaining > 0) {
|
8199 | if (++count >= HOT_COUNT) {
|
8200 | return key;
|
8201 | }
|
8202 | } else {
|
8203 | count = 0;
|
8204 | }
|
8205 | return baseSetData(key, value);
|
8206 | };
|
8207 | }());
|
8208 |
|
8209 | /**
|
8210 | * A fallback implementation of `Object.keys` which creates an array of the
|
8211 | * own enumerable property names of `object`.
|
8212 | *
|
8213 | * @private
|
8214 | * @param {Object} object The object to query.
|
8215 | * @returns {Array} Returns the array of property names.
|
8216 | */
|
8217 | function shimKeys(object) {
|
8218 | var props = keysIn(object),
|
8219 | propsLength = props.length,
|
8220 | length = propsLength && object.length;
|
8221 |
|
8222 | var allowIndexes = !!length && isLength(length) &&
|
8223 | (isArray(object) || isArguments(object));
|
8224 |
|
8225 | var index = -1,
|
8226 | result = [];
|
8227 |
|
8228 | while (++index < propsLength) {
|
8229 | var key = props[index];
|
8230 | if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
|
8231 | result.push(key);
|
8232 | }
|
8233 | }
|
8234 | return result;
|
8235 | }
|
8236 |
|
8237 | /**
|
8238 | * Converts `value` to an array-like object if it's not one.
|
8239 | *
|
8240 | * @private
|
8241 | * @param {*} value The value to process.
|
8242 | * @returns {Array|Object} Returns the array-like object.
|
8243 | */
|
8244 | function toIterable(value) {
|
8245 | if (value == null) {
|
8246 | return [];
|
8247 | }
|
8248 | if (!isArrayLike(value)) {
|
8249 | return values(value);
|
8250 | }
|
8251 | return isObject(value) ? value : Object(value);
|
8252 | }
|
8253 |
|
8254 | /**
|
8255 | * Converts `value` to an object if it's not one.
|
8256 | *
|
8257 | * @private
|
8258 | * @param {*} value The value to process.
|
8259 | * @returns {Object} Returns the object.
|
8260 | */
|
8261 | function toObject(value) {
|
8262 | return isObject(value) ? value : Object(value);
|
8263 | }
|
8264 |
|
8265 | /**
|
8266 | * Converts `value` to property path array if it's not one.
|
8267 | *
|
8268 | * @private
|
8269 | * @param {*} value The value to process.
|
8270 | * @returns {Array} Returns the property path array.
|
8271 | */
|
8272 | function toPath(value) {
|
8273 | if (isArray(value)) {
|
8274 | return value;
|
8275 | }
|
8276 | var result = [];
|
8277 | baseToString(value).replace(rePropName, function(match, number, quote, string) {
|
8278 | result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
|
8279 | });
|
8280 | return result;
|
8281 | }
|
8282 |
|
8283 | /**
|
8284 | * Creates a clone of `wrapper`.
|
8285 | *
|
8286 | * @private
|
8287 | * @param {Object} wrapper The wrapper to clone.
|
8288 | * @returns {Object} Returns the cloned wrapper.
|
8289 | */
|
8290 | function wrapperClone(wrapper) {
|
8291 | return wrapper instanceof LazyWrapper
|
8292 | ? wrapper.clone()
|
8293 | : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
|
8294 | }
|
8295 |
|
8296 | /*------------------------------------------------------------------------*/
|
8297 |
|
8298 | /**
|
8299 | * Creates an array of elements split into groups the length of `size`.
|
8300 | * If `collection` can't be split evenly, the final chunk will be the remaining
|
8301 | * elements.
|
8302 | *
|
8303 | * @static
|
8304 | * @memberOf _
|
8305 | * @category Array
|
8306 | * @param {Array} array The array to process.
|
8307 | * @param {number} [size=1] The length of each chunk.
|
8308 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
8309 | * @returns {Array} Returns the new array containing chunks.
|
8310 | * @example
|
8311 | *
|
8312 | * _.chunk(['a', 'b', 'c', 'd'], 2);
|
8313 | * // => [['a', 'b'], ['c', 'd']]
|
8314 | *
|
8315 | * _.chunk(['a', 'b', 'c', 'd'], 3);
|
8316 | * // => [['a', 'b', 'c'], ['d']]
|
8317 | */
|
8318 | function chunk(array, size, guard) {
|
8319 | if (guard ? isIterateeCall(array, size, guard) : size == null) {
|
8320 | size = 1;
|
8321 | } else {
|
8322 | size = nativeMax(nativeFloor(size) || 1, 1);
|
8323 | }
|
8324 | var index = 0,
|
8325 | length = array ? array.length : 0,
|
8326 | resIndex = -1,
|
8327 | result = Array(nativeCeil(length / size));
|
8328 |
|
8329 | while (index < length) {
|
8330 | result[++resIndex] = baseSlice(array, index, (index += size));
|
8331 | }
|
8332 | return result;
|
8333 | }
|
8334 |
|
8335 | /**
|
8336 | * Creates an array with all falsey values removed. The values `false`, `null`,
|
8337 | * `0`, `""`, `undefined`, and `NaN` are falsey.
|
8338 | *
|
8339 | * @static
|
8340 | * @memberOf _
|
8341 | * @category Array
|
8342 | * @param {Array} array The array to compact.
|
8343 | * @returns {Array} Returns the new array of filtered values.
|
8344 | * @example
|
8345 | *
|
8346 | * _.compact([0, 1, false, 2, '', 3]);
|
8347 | * // => [1, 2, 3]
|
8348 | */
|
8349 | function compact(array) {
|
8350 | var index = -1,
|
8351 | length = array ? array.length : 0,
|
8352 | resIndex = -1,
|
8353 | result = [];
|
8354 |
|
8355 | while (++index < length) {
|
8356 | var value = array[index];
|
8357 | if (value) {
|
8358 | result[++resIndex] = value;
|
8359 | }
|
8360 | }
|
8361 | return result;
|
8362 | }
|
8363 |
|
8364 | /**
|
8365 | * Creates an array of unique `array` values not included in the other
|
8366 | * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
|
8367 | * for equality comparisons.
|
8368 | *
|
8369 | * @static
|
8370 | * @memberOf _
|
8371 | * @category Array
|
8372 | * @param {Array} array The array to inspect.
|
8373 | * @param {...Array} [values] The arrays of values to exclude.
|
8374 | * @returns {Array} Returns the new array of filtered values.
|
8375 | * @example
|
8376 | *
|
8377 | * _.difference([1, 2, 3], [4, 2]);
|
8378 | * // => [1, 3]
|
8379 | */
|
8380 | var difference = restParam(function(array, values) {
|
8381 | return (isObjectLike(array) && isArrayLike(array))
|
8382 | ? baseDifference(array, baseFlatten(values, false, true))
|
8383 | : [];
|
8384 | });
|
8385 |
|
8386 | /**
|
8387 | * Creates a slice of `array` with `n` elements dropped from the beginning.
|
8388 | *
|
8389 | * @static
|
8390 | * @memberOf _
|
8391 | * @category Array
|
8392 | * @param {Array} array The array to query.
|
8393 | * @param {number} [n=1] The number of elements to drop.
|
8394 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
8395 | * @returns {Array} Returns the slice of `array`.
|
8396 | * @example
|
8397 | *
|
8398 | * _.drop([1, 2, 3]);
|
8399 | * // => [2, 3]
|
8400 | *
|
8401 | * _.drop([1, 2, 3], 2);
|
8402 | * // => [3]
|
8403 | *
|
8404 | * _.drop([1, 2, 3], 5);
|
8405 | * // => []
|
8406 | *
|
8407 | * _.drop([1, 2, 3], 0);
|
8408 | * // => [1, 2, 3]
|
8409 | */
|
8410 | function drop(array, n, guard) {
|
8411 | var length = array ? array.length : 0;
|
8412 | if (!length) {
|
8413 | return [];
|
8414 | }
|
8415 | if (guard ? isIterateeCall(array, n, guard) : n == null) {
|
8416 | n = 1;
|
8417 | }
|
8418 | return baseSlice(array, n < 0 ? 0 : n);
|
8419 | }
|
8420 |
|
8421 | /**
|
8422 | * Creates a slice of `array` with `n` elements dropped from the end.
|
8423 | *
|
8424 | * @static
|
8425 | * @memberOf _
|
8426 | * @category Array
|
8427 | * @param {Array} array The array to query.
|
8428 | * @param {number} [n=1] The number of elements to drop.
|
8429 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
8430 | * @returns {Array} Returns the slice of `array`.
|
8431 | * @example
|
8432 | *
|
8433 | * _.dropRight([1, 2, 3]);
|
8434 | * // => [1, 2]
|
8435 | *
|
8436 | * _.dropRight([1, 2, 3], 2);
|
8437 | * // => [1]
|
8438 | *
|
8439 | * _.dropRight([1, 2, 3], 5);
|
8440 | * // => []
|
8441 | *
|
8442 | * _.dropRight([1, 2, 3], 0);
|
8443 | * // => [1, 2, 3]
|
8444 | */
|
8445 | function dropRight(array, n, guard) {
|
8446 | var length = array ? array.length : 0;
|
8447 | if (!length) {
|
8448 | return [];
|
8449 | }
|
8450 | if (guard ? isIterateeCall(array, n, guard) : n == null) {
|
8451 | n = 1;
|
8452 | }
|
8453 | n = length - (+n || 0);
|
8454 | return baseSlice(array, 0, n < 0 ? 0 : n);
|
8455 | }
|
8456 |
|
8457 | /**
|
8458 | * Creates a slice of `array` excluding elements dropped from the end.
|
8459 | * Elements are dropped until `predicate` returns falsey. The predicate is
|
8460 | * bound to `thisArg` and invoked with three arguments: (value, index, array).
|
8461 | *
|
8462 | * If a property name is provided for `predicate` the created `_.property`
|
8463 | * style callback returns the property value of the given element.
|
8464 | *
|
8465 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
8466 | * style callback returns `true` for elements that have a matching property
|
8467 | * value, else `false`.
|
8468 | *
|
8469 | * If an object is provided for `predicate` the created `_.matches` style
|
8470 | * callback returns `true` for elements that match the properties of the given
|
8471 | * object, else `false`.
|
8472 | *
|
8473 | * @static
|
8474 | * @memberOf _
|
8475 | * @category Array
|
8476 | * @param {Array} array The array to query.
|
8477 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
8478 | * per iteration.
|
8479 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
8480 | * @returns {Array} Returns the slice of `array`.
|
8481 | * @example
|
8482 | *
|
8483 | * _.dropRightWhile([1, 2, 3], function(n) {
|
8484 | * return n > 1;
|
8485 | * });
|
8486 | * // => [1]
|
8487 | *
|
8488 | * var users = [
|
8489 | * { 'user': 'barney', 'active': true },
|
8490 | * { 'user': 'fred', 'active': false },
|
8491 | * { 'user': 'pebbles', 'active': false }
|
8492 | * ];
|
8493 | *
|
8494 | * // using the `_.matches` callback shorthand
|
8495 | * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
|
8496 | * // => ['barney', 'fred']
|
8497 | *
|
8498 | * // using the `_.matchesProperty` callback shorthand
|
8499 | * _.pluck(_.dropRightWhile(users, 'active', false), 'user');
|
8500 | * // => ['barney']
|
8501 | *
|
8502 | * // using the `_.property` callback shorthand
|
8503 | * _.pluck(_.dropRightWhile(users, 'active'), 'user');
|
8504 | * // => ['barney', 'fred', 'pebbles']
|
8505 | */
|
8506 | function dropRightWhile(array, predicate, thisArg) {
|
8507 | return (array && array.length)
|
8508 | ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true)
|
8509 | : [];
|
8510 | }
|
8511 |
|
8512 | /**
|
8513 | * Creates a slice of `array` excluding elements dropped from the beginning.
|
8514 | * Elements are dropped until `predicate` returns falsey. The predicate is
|
8515 | * bound to `thisArg` and invoked with three arguments: (value, index, array).
|
8516 | *
|
8517 | * If a property name is provided for `predicate` the created `_.property`
|
8518 | * style callback returns the property value of the given element.
|
8519 | *
|
8520 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
8521 | * style callback returns `true` for elements that have a matching property
|
8522 | * value, else `false`.
|
8523 | *
|
8524 | * If an object is provided for `predicate` the created `_.matches` style
|
8525 | * callback returns `true` for elements that have the properties of the given
|
8526 | * object, else `false`.
|
8527 | *
|
8528 | * @static
|
8529 | * @memberOf _
|
8530 | * @category Array
|
8531 | * @param {Array} array The array to query.
|
8532 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
8533 | * per iteration.
|
8534 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
8535 | * @returns {Array} Returns the slice of `array`.
|
8536 | * @example
|
8537 | *
|
8538 | * _.dropWhile([1, 2, 3], function(n) {
|
8539 | * return n < 3;
|
8540 | * });
|
8541 | * // => [3]
|
8542 | *
|
8543 | * var users = [
|
8544 | * { 'user': 'barney', 'active': false },
|
8545 | * { 'user': 'fred', 'active': false },
|
8546 | * { 'user': 'pebbles', 'active': true }
|
8547 | * ];
|
8548 | *
|
8549 | * // using the `_.matches` callback shorthand
|
8550 | * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
|
8551 | * // => ['fred', 'pebbles']
|
8552 | *
|
8553 | * // using the `_.matchesProperty` callback shorthand
|
8554 | * _.pluck(_.dropWhile(users, 'active', false), 'user');
|
8555 | * // => ['pebbles']
|
8556 | *
|
8557 | * // using the `_.property` callback shorthand
|
8558 | * _.pluck(_.dropWhile(users, 'active'), 'user');
|
8559 | * // => ['barney', 'fred', 'pebbles']
|
8560 | */
|
8561 | function dropWhile(array, predicate, thisArg) {
|
8562 | return (array && array.length)
|
8563 | ? baseWhile(array, getCallback(predicate, thisArg, 3), true)
|
8564 | : [];
|
8565 | }
|
8566 |
|
8567 | /**
|
8568 | * Fills elements of `array` with `value` from `start` up to, but not
|
8569 | * including, `end`.
|
8570 | *
|
8571 | * **Note:** This method mutates `array`.
|
8572 | *
|
8573 | * @static
|
8574 | * @memberOf _
|
8575 | * @category Array
|
8576 | * @param {Array} array The array to fill.
|
8577 | * @param {*} value The value to fill `array` with.
|
8578 | * @param {number} [start=0] The start position.
|
8579 | * @param {number} [end=array.length] The end position.
|
8580 | * @returns {Array} Returns `array`.
|
8581 | * @example
|
8582 | *
|
8583 | * var array = [1, 2, 3];
|
8584 | *
|
8585 | * _.fill(array, 'a');
|
8586 | * console.log(array);
|
8587 | * // => ['a', 'a', 'a']
|
8588 | *
|
8589 | * _.fill(Array(3), 2);
|
8590 | * // => [2, 2, 2]
|
8591 | *
|
8592 | * _.fill([4, 6, 8], '*', 1, 2);
|
8593 | * // => [4, '*', 8]
|
8594 | */
|
8595 | function fill(array, value, start, end) {
|
8596 | var length = array ? array.length : 0;
|
8597 | if (!length) {
|
8598 | return [];
|
8599 | }
|
8600 | if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
|
8601 | start = 0;
|
8602 | end = length;
|
8603 | }
|
8604 | return baseFill(array, value, start, end);
|
8605 | }
|
8606 |
|
8607 | /**
|
8608 | * This method is like `_.find` except that it returns the index of the first
|
8609 | * element `predicate` returns truthy for instead of the element itself.
|
8610 | *
|
8611 | * If a property name is provided for `predicate` the created `_.property`
|
8612 | * style callback returns the property value of the given element.
|
8613 | *
|
8614 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
8615 | * style callback returns `true` for elements that have a matching property
|
8616 | * value, else `false`.
|
8617 | *
|
8618 | * If an object is provided for `predicate` the created `_.matches` style
|
8619 | * callback returns `true` for elements that have the properties of the given
|
8620 | * object, else `false`.
|
8621 | *
|
8622 | * @static
|
8623 | * @memberOf _
|
8624 | * @category Array
|
8625 | * @param {Array} array The array to search.
|
8626 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
8627 | * per iteration.
|
8628 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
8629 | * @returns {number} Returns the index of the found element, else `-1`.
|
8630 | * @example
|
8631 | *
|
8632 | * var users = [
|
8633 | * { 'user': 'barney', 'active': false },
|
8634 | * { 'user': 'fred', 'active': false },
|
8635 | * { 'user': 'pebbles', 'active': true }
|
8636 | * ];
|
8637 | *
|
8638 | * _.findIndex(users, function(chr) {
|
8639 | * return chr.user == 'barney';
|
8640 | * });
|
8641 | * // => 0
|
8642 | *
|
8643 | * // using the `_.matches` callback shorthand
|
8644 | * _.findIndex(users, { 'user': 'fred', 'active': false });
|
8645 | * // => 1
|
8646 | *
|
8647 | * // using the `_.matchesProperty` callback shorthand
|
8648 | * _.findIndex(users, 'active', false);
|
8649 | * // => 0
|
8650 | *
|
8651 | * // using the `_.property` callback shorthand
|
8652 | * _.findIndex(users, 'active');
|
8653 | * // => 2
|
8654 | */
|
8655 | var findIndex = createFindIndex();
|
8656 |
|
8657 | /**
|
8658 | * This method is like `_.findIndex` except that it iterates over elements
|
8659 | * of `collection` from right to left.
|
8660 | *
|
8661 | * If a property name is provided for `predicate` the created `_.property`
|
8662 | * style callback returns the property value of the given element.
|
8663 | *
|
8664 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
8665 | * style callback returns `true` for elements that have a matching property
|
8666 | * value, else `false`.
|
8667 | *
|
8668 | * If an object is provided for `predicate` the created `_.matches` style
|
8669 | * callback returns `true` for elements that have the properties of the given
|
8670 | * object, else `false`.
|
8671 | *
|
8672 | * @static
|
8673 | * @memberOf _
|
8674 | * @category Array
|
8675 | * @param {Array} array The array to search.
|
8676 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
8677 | * per iteration.
|
8678 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
8679 | * @returns {number} Returns the index of the found element, else `-1`.
|
8680 | * @example
|
8681 | *
|
8682 | * var users = [
|
8683 | * { 'user': 'barney', 'active': true },
|
8684 | * { 'user': 'fred', 'active': false },
|
8685 | * { 'user': 'pebbles', 'active': false }
|
8686 | * ];
|
8687 | *
|
8688 | * _.findLastIndex(users, function(chr) {
|
8689 | * return chr.user == 'pebbles';
|
8690 | * });
|
8691 | * // => 2
|
8692 | *
|
8693 | * // using the `_.matches` callback shorthand
|
8694 | * _.findLastIndex(users, { 'user': 'barney', 'active': true });
|
8695 | * // => 0
|
8696 | *
|
8697 | * // using the `_.matchesProperty` callback shorthand
|
8698 | * _.findLastIndex(users, 'active', false);
|
8699 | * // => 2
|
8700 | *
|
8701 | * // using the `_.property` callback shorthand
|
8702 | * _.findLastIndex(users, 'active');
|
8703 | * // => 0
|
8704 | */
|
8705 | var findLastIndex = createFindIndex(true);
|
8706 |
|
8707 | /**
|
8708 | * Gets the first element of `array`.
|
8709 | *
|
8710 | * @static
|
8711 | * @memberOf _
|
8712 | * @alias head
|
8713 | * @category Array
|
8714 | * @param {Array} array The array to query.
|
8715 | * @returns {*} Returns the first element of `array`.
|
8716 | * @example
|
8717 | *
|
8718 | * _.first([1, 2, 3]);
|
8719 | * // => 1
|
8720 | *
|
8721 | * _.first([]);
|
8722 | * // => undefined
|
8723 | */
|
8724 | function first(array) {
|
8725 | return array ? array[0] : undefined;
|
8726 | }
|
8727 |
|
8728 | /**
|
8729 | * Flattens a nested array. If `isDeep` is `true` the array is recursively
|
8730 | * flattened, otherwise it is only flattened a single level.
|
8731 | *
|
8732 | * @static
|
8733 | * @memberOf _
|
8734 | * @category Array
|
8735 | * @param {Array} array The array to flatten.
|
8736 | * @param {boolean} [isDeep] Specify a deep flatten.
|
8737 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
8738 | * @returns {Array} Returns the new flattened array.
|
8739 | * @example
|
8740 | *
|
8741 | * _.flatten([1, [2, 3, [4]]]);
|
8742 | * // => [1, 2, 3, [4]]
|
8743 | *
|
8744 | * // using `isDeep`
|
8745 | * _.flatten([1, [2, 3, [4]]], true);
|
8746 | * // => [1, 2, 3, 4]
|
8747 | */
|
8748 | function flatten(array, isDeep, guard) {
|
8749 | var length = array ? array.length : 0;
|
8750 | if (guard && isIterateeCall(array, isDeep, guard)) {
|
8751 | isDeep = false;
|
8752 | }
|
8753 | return length ? baseFlatten(array, isDeep) : [];
|
8754 | }
|
8755 |
|
8756 | /**
|
8757 | * Recursively flattens a nested array.
|
8758 | *
|
8759 | * @static
|
8760 | * @memberOf _
|
8761 | * @category Array
|
8762 | * @param {Array} array The array to recursively flatten.
|
8763 | * @returns {Array} Returns the new flattened array.
|
8764 | * @example
|
8765 | *
|
8766 | * _.flattenDeep([1, [2, 3, [4]]]);
|
8767 | * // => [1, 2, 3, 4]
|
8768 | */
|
8769 | function flattenDeep(array) {
|
8770 | var length = array ? array.length : 0;
|
8771 | return length ? baseFlatten(array, true) : [];
|
8772 | }
|
8773 |
|
8774 | /**
|
8775 | * Gets the index at which the first occurrence of `value` is found in `array`
|
8776 | * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
|
8777 | * for equality comparisons. If `fromIndex` is negative, it is used as the offset
|
8778 | * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
|
8779 | * performs a faster binary search.
|
8780 | *
|
8781 | * @static
|
8782 | * @memberOf _
|
8783 | * @category Array
|
8784 | * @param {Array} array The array to search.
|
8785 | * @param {*} value The value to search for.
|
8786 | * @param {boolean|number} [fromIndex=0] The index to search from or `true`
|
8787 | * to perform a binary search on a sorted array.
|
8788 | * @returns {number} Returns the index of the matched value, else `-1`.
|
8789 | * @example
|
8790 | *
|
8791 | * _.indexOf([1, 2, 1, 2], 2);
|
8792 | * // => 1
|
8793 | *
|
8794 | * // using `fromIndex`
|
8795 | * _.indexOf([1, 2, 1, 2], 2, 2);
|
8796 | * // => 3
|
8797 | *
|
8798 | * // performing a binary search
|
8799 | * _.indexOf([1, 1, 2, 2], 2, true);
|
8800 | * // => 2
|
8801 | */
|
8802 | function indexOf(array, value, fromIndex) {
|
8803 | var length = array ? array.length : 0;
|
8804 | if (!length) {
|
8805 | return -1;
|
8806 | }
|
8807 | if (typeof fromIndex == 'number') {
|
8808 | fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
|
8809 | } else if (fromIndex) {
|
8810 | var index = binaryIndex(array, value);
|
8811 | if (index < length &&
|
8812 | (value === value ? (value === array[index]) : (array[index] !== array[index]))) {
|
8813 | return index;
|
8814 | }
|
8815 | return -1;
|
8816 | }
|
8817 | return baseIndexOf(array, value, fromIndex || 0);
|
8818 | }
|
8819 |
|
8820 | /**
|
8821 | * Gets all but the last element of `array`.
|
8822 | *
|
8823 | * @static
|
8824 | * @memberOf _
|
8825 | * @category Array
|
8826 | * @param {Array} array The array to query.
|
8827 | * @returns {Array} Returns the slice of `array`.
|
8828 | * @example
|
8829 | *
|
8830 | * _.initial([1, 2, 3]);
|
8831 | * // => [1, 2]
|
8832 | */
|
8833 | function initial(array) {
|
8834 | return dropRight(array, 1);
|
8835 | }
|
8836 |
|
8837 | /**
|
8838 | * Creates an array of unique values that are included in all of the provided
|
8839 | * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
|
8840 | * for equality comparisons.
|
8841 | *
|
8842 | * @static
|
8843 | * @memberOf _
|
8844 | * @category Array
|
8845 | * @param {...Array} [arrays] The arrays to inspect.
|
8846 | * @returns {Array} Returns the new array of shared values.
|
8847 | * @example
|
8848 | * _.intersection([1, 2], [4, 2], [2, 1]);
|
8849 | * // => [2]
|
8850 | */
|
8851 | var intersection = restParam(function(arrays) {
|
8852 | var othLength = arrays.length,
|
8853 | othIndex = othLength,
|
8854 | caches = Array(length),
|
8855 | indexOf = getIndexOf(),
|
8856 | isCommon = indexOf == baseIndexOf,
|
8857 | result = [];
|
8858 |
|
8859 | while (othIndex--) {
|
8860 | var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
|
8861 | caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
|
8862 | }
|
8863 | var array = arrays[0],
|
8864 | index = -1,
|
8865 | length = array ? array.length : 0,
|
8866 | seen = caches[0];
|
8867 |
|
8868 | outer:
|
8869 | while (++index < length) {
|
8870 | value = array[index];
|
8871 | if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
|
8872 | var othIndex = othLength;
|
8873 | while (--othIndex) {
|
8874 | var cache = caches[othIndex];
|
8875 | if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
|
8876 | continue outer;
|
8877 | }
|
8878 | }
|
8879 | if (seen) {
|
8880 | seen.push(value);
|
8881 | }
|
8882 | result.push(value);
|
8883 | }
|
8884 | }
|
8885 | return result;
|
8886 | });
|
8887 |
|
8888 | /**
|
8889 | * Gets the last element of `array`.
|
8890 | *
|
8891 | * @static
|
8892 | * @memberOf _
|
8893 | * @category Array
|
8894 | * @param {Array} array The array to query.
|
8895 | * @returns {*} Returns the last element of `array`.
|
8896 | * @example
|
8897 | *
|
8898 | * _.last([1, 2, 3]);
|
8899 | * // => 3
|
8900 | */
|
8901 | function last(array) {
|
8902 | var length = array ? array.length : 0;
|
8903 | return length ? array[length - 1] : undefined;
|
8904 | }
|
8905 |
|
8906 | /**
|
8907 | * This method is like `_.indexOf` except that it iterates over elements of
|
8908 | * `array` from right to left.
|
8909 | *
|
8910 | * @static
|
8911 | * @memberOf _
|
8912 | * @category Array
|
8913 | * @param {Array} array The array to search.
|
8914 | * @param {*} value The value to search for.
|
8915 | * @param {boolean|number} [fromIndex=array.length-1] The index to search from
|
8916 | * or `true` to perform a binary search on a sorted array.
|
8917 | * @returns {number} Returns the index of the matched value, else `-1`.
|
8918 | * @example
|
8919 | *
|
8920 | * _.lastIndexOf([1, 2, 1, 2], 2);
|
8921 | * // => 3
|
8922 | *
|
8923 | * // using `fromIndex`
|
8924 | * _.lastIndexOf([1, 2, 1, 2], 2, 2);
|
8925 | * // => 1
|
8926 | *
|
8927 | * // performing a binary search
|
8928 | * _.lastIndexOf([1, 1, 2, 2], 2, true);
|
8929 | * // => 3
|
8930 | */
|
8931 | function lastIndexOf(array, value, fromIndex) {
|
8932 | var length = array ? array.length : 0;
|
8933 | if (!length) {
|
8934 | return -1;
|
8935 | }
|
8936 | var index = length;
|
8937 | if (typeof fromIndex == 'number') {
|
8938 | index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
|
8939 | } else if (fromIndex) {
|
8940 | index = binaryIndex(array, value, true) - 1;
|
8941 | var other = array[index];
|
8942 | if (value === value ? (value === other) : (other !== other)) {
|
8943 | return index;
|
8944 | }
|
8945 | return -1;
|
8946 | }
|
8947 | if (value !== value) {
|
8948 | return indexOfNaN(array, index, true);
|
8949 | }
|
8950 | while (index--) {
|
8951 | if (array[index] === value) {
|
8952 | return index;
|
8953 | }
|
8954 | }
|
8955 | return -1;
|
8956 | }
|
8957 |
|
8958 | /**
|
8959 | * Removes all provided values from `array` using
|
8960 | * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
|
8961 | * for equality comparisons.
|
8962 | *
|
8963 | * **Note:** Unlike `_.without`, this method mutates `array`.
|
8964 | *
|
8965 | * @static
|
8966 | * @memberOf _
|
8967 | * @category Array
|
8968 | * @param {Array} array The array to modify.
|
8969 | * @param {...*} [values] The values to remove.
|
8970 | * @returns {Array} Returns `array`.
|
8971 | * @example
|
8972 | *
|
8973 | * var array = [1, 2, 3, 1, 2, 3];
|
8974 | *
|
8975 | * _.pull(array, 2, 3);
|
8976 | * console.log(array);
|
8977 | * // => [1, 1]
|
8978 | */
|
8979 | function pull() {
|
8980 | var args = arguments,
|
8981 | array = args[0];
|
8982 |
|
8983 | if (!(array && array.length)) {
|
8984 | return array;
|
8985 | }
|
8986 | var index = 0,
|
8987 | indexOf = getIndexOf(),
|
8988 | length = args.length;
|
8989 |
|
8990 | while (++index < length) {
|
8991 | var fromIndex = 0,
|
8992 | value = args[index];
|
8993 |
|
8994 | while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
|
8995 | splice.call(array, fromIndex, 1);
|
8996 | }
|
8997 | }
|
8998 | return array;
|
8999 | }
|
9000 |
|
9001 | /**
|
9002 | * Removes elements from `array` corresponding to the given indexes and returns
|
9003 | * an array of the removed elements. Indexes may be specified as an array of
|
9004 | * indexes or as individual arguments.
|
9005 | *
|
9006 | * **Note:** Unlike `_.at`, this method mutates `array`.
|
9007 | *
|
9008 | * @static
|
9009 | * @memberOf _
|
9010 | * @category Array
|
9011 | * @param {Array} array The array to modify.
|
9012 | * @param {...(number|number[])} [indexes] The indexes of elements to remove,
|
9013 | * specified as individual indexes or arrays of indexes.
|
9014 | * @returns {Array} Returns the new array of removed elements.
|
9015 | * @example
|
9016 | *
|
9017 | * var array = [5, 10, 15, 20];
|
9018 | * var evens = _.pullAt(array, 1, 3);
|
9019 | *
|
9020 | * console.log(array);
|
9021 | * // => [5, 15]
|
9022 | *
|
9023 | * console.log(evens);
|
9024 | * // => [10, 20]
|
9025 | */
|
9026 | var pullAt = restParam(function(array, indexes) {
|
9027 | indexes = baseFlatten(indexes);
|
9028 |
|
9029 | var result = baseAt(array, indexes);
|
9030 | basePullAt(array, indexes.sort(baseCompareAscending));
|
9031 | return result;
|
9032 | });
|
9033 |
|
9034 | /**
|
9035 | * Removes all elements from `array` that `predicate` returns truthy for
|
9036 | * and returns an array of the removed elements. The predicate is bound to
|
9037 | * `thisArg` and invoked with three arguments: (value, index, array).
|
9038 | *
|
9039 | * If a property name is provided for `predicate` the created `_.property`
|
9040 | * style callback returns the property value of the given element.
|
9041 | *
|
9042 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
9043 | * style callback returns `true` for elements that have a matching property
|
9044 | * value, else `false`.
|
9045 | *
|
9046 | * If an object is provided for `predicate` the created `_.matches` style
|
9047 | * callback returns `true` for elements that have the properties of the given
|
9048 | * object, else `false`.
|
9049 | *
|
9050 | * **Note:** Unlike `_.filter`, this method mutates `array`.
|
9051 | *
|
9052 | * @static
|
9053 | * @memberOf _
|
9054 | * @category Array
|
9055 | * @param {Array} array The array to modify.
|
9056 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
9057 | * per iteration.
|
9058 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
9059 | * @returns {Array} Returns the new array of removed elements.
|
9060 | * @example
|
9061 | *
|
9062 | * var array = [1, 2, 3, 4];
|
9063 | * var evens = _.remove(array, function(n) {
|
9064 | * return n % 2 == 0;
|
9065 | * });
|
9066 | *
|
9067 | * console.log(array);
|
9068 | * // => [1, 3]
|
9069 | *
|
9070 | * console.log(evens);
|
9071 | * // => [2, 4]
|
9072 | */
|
9073 | function remove(array, predicate, thisArg) {
|
9074 | var result = [];
|
9075 | if (!(array && array.length)) {
|
9076 | return result;
|
9077 | }
|
9078 | var index = -1,
|
9079 | indexes = [],
|
9080 | length = array.length;
|
9081 |
|
9082 | predicate = getCallback(predicate, thisArg, 3);
|
9083 | while (++index < length) {
|
9084 | var value = array[index];
|
9085 | if (predicate(value, index, array)) {
|
9086 | result.push(value);
|
9087 | indexes.push(index);
|
9088 | }
|
9089 | }
|
9090 | basePullAt(array, indexes);
|
9091 | return result;
|
9092 | }
|
9093 |
|
9094 | /**
|
9095 | * Gets all but the first element of `array`.
|
9096 | *
|
9097 | * @static
|
9098 | * @memberOf _
|
9099 | * @alias tail
|
9100 | * @category Array
|
9101 | * @param {Array} array The array to query.
|
9102 | * @returns {Array} Returns the slice of `array`.
|
9103 | * @example
|
9104 | *
|
9105 | * _.rest([1, 2, 3]);
|
9106 | * // => [2, 3]
|
9107 | */
|
9108 | function rest(array) {
|
9109 | return drop(array, 1);
|
9110 | }
|
9111 |
|
9112 | /**
|
9113 | * Creates a slice of `array` from `start` up to, but not including, `end`.
|
9114 | *
|
9115 | * **Note:** This method is used instead of `Array#slice` to support node
|
9116 | * lists in IE < 9 and to ensure dense arrays are returned.
|
9117 | *
|
9118 | * @static
|
9119 | * @memberOf _
|
9120 | * @category Array
|
9121 | * @param {Array} array The array to slice.
|
9122 | * @param {number} [start=0] The start position.
|
9123 | * @param {number} [end=array.length] The end position.
|
9124 | * @returns {Array} Returns the slice of `array`.
|
9125 | */
|
9126 | function slice(array, start, end) {
|
9127 | var length = array ? array.length : 0;
|
9128 | if (!length) {
|
9129 | return [];
|
9130 | }
|
9131 | if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
|
9132 | start = 0;
|
9133 | end = length;
|
9134 | }
|
9135 | return baseSlice(array, start, end);
|
9136 | }
|
9137 |
|
9138 | /**
|
9139 | * Uses a binary search to determine the lowest index at which `value` should
|
9140 | * be inserted into `array` in order to maintain its sort order. If an iteratee
|
9141 | * function is provided it is invoked for `value` and each element of `array`
|
9142 | * to compute their sort ranking. The iteratee is bound to `thisArg` and
|
9143 | * invoked with one argument; (value).
|
9144 | *
|
9145 | * If a property name is provided for `iteratee` the created `_.property`
|
9146 | * style callback returns the property value of the given element.
|
9147 | *
|
9148 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
9149 | * style callback returns `true` for elements that have a matching property
|
9150 | * value, else `false`.
|
9151 | *
|
9152 | * If an object is provided for `iteratee` the created `_.matches` style
|
9153 | * callback returns `true` for elements that have the properties of the given
|
9154 | * object, else `false`.
|
9155 | *
|
9156 | * @static
|
9157 | * @memberOf _
|
9158 | * @category Array
|
9159 | * @param {Array} array The sorted array to inspect.
|
9160 | * @param {*} value The value to evaluate.
|
9161 | * @param {Function|Object|string} [iteratee=_.identity] The function invoked
|
9162 | * per iteration.
|
9163 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
9164 | * @returns {number} Returns the index at which `value` should be inserted
|
9165 | * into `array`.
|
9166 | * @example
|
9167 | *
|
9168 | * _.sortedIndex([30, 50], 40);
|
9169 | * // => 1
|
9170 | *
|
9171 | * _.sortedIndex([4, 4, 5, 5], 5);
|
9172 | * // => 2
|
9173 | *
|
9174 | * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
|
9175 | *
|
9176 | * // using an iteratee function
|
9177 | * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
|
9178 | * return this.data[word];
|
9179 | * }, dict);
|
9180 | * // => 1
|
9181 | *
|
9182 | * // using the `_.property` callback shorthand
|
9183 | * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
|
9184 | * // => 1
|
9185 | */
|
9186 | var sortedIndex = createSortedIndex();
|
9187 |
|
9188 | /**
|
9189 | * This method is like `_.sortedIndex` except that it returns the highest
|
9190 | * index at which `value` should be inserted into `array` in order to
|
9191 | * maintain its sort order.
|
9192 | *
|
9193 | * @static
|
9194 | * @memberOf _
|
9195 | * @category Array
|
9196 | * @param {Array} array The sorted array to inspect.
|
9197 | * @param {*} value The value to evaluate.
|
9198 | * @param {Function|Object|string} [iteratee=_.identity] The function invoked
|
9199 | * per iteration.
|
9200 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
9201 | * @returns {number} Returns the index at which `value` should be inserted
|
9202 | * into `array`.
|
9203 | * @example
|
9204 | *
|
9205 | * _.sortedLastIndex([4, 4, 5, 5], 5);
|
9206 | * // => 4
|
9207 | */
|
9208 | var sortedLastIndex = createSortedIndex(true);
|
9209 |
|
9210 | /**
|
9211 | * Creates a slice of `array` with `n` elements taken from the beginning.
|
9212 | *
|
9213 | * @static
|
9214 | * @memberOf _
|
9215 | * @category Array
|
9216 | * @param {Array} array The array to query.
|
9217 | * @param {number} [n=1] The number of elements to take.
|
9218 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
9219 | * @returns {Array} Returns the slice of `array`.
|
9220 | * @example
|
9221 | *
|
9222 | * _.take([1, 2, 3]);
|
9223 | * // => [1]
|
9224 | *
|
9225 | * _.take([1, 2, 3], 2);
|
9226 | * // => [1, 2]
|
9227 | *
|
9228 | * _.take([1, 2, 3], 5);
|
9229 | * // => [1, 2, 3]
|
9230 | *
|
9231 | * _.take([1, 2, 3], 0);
|
9232 | * // => []
|
9233 | */
|
9234 | function take(array, n, guard) {
|
9235 | var length = array ? array.length : 0;
|
9236 | if (!length) {
|
9237 | return [];
|
9238 | }
|
9239 | if (guard ? isIterateeCall(array, n, guard) : n == null) {
|
9240 | n = 1;
|
9241 | }
|
9242 | return baseSlice(array, 0, n < 0 ? 0 : n);
|
9243 | }
|
9244 |
|
9245 | /**
|
9246 | * Creates a slice of `array` with `n` elements taken from the end.
|
9247 | *
|
9248 | * @static
|
9249 | * @memberOf _
|
9250 | * @category Array
|
9251 | * @param {Array} array The array to query.
|
9252 | * @param {number} [n=1] The number of elements to take.
|
9253 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
9254 | * @returns {Array} Returns the slice of `array`.
|
9255 | * @example
|
9256 | *
|
9257 | * _.takeRight([1, 2, 3]);
|
9258 | * // => [3]
|
9259 | *
|
9260 | * _.takeRight([1, 2, 3], 2);
|
9261 | * // => [2, 3]
|
9262 | *
|
9263 | * _.takeRight([1, 2, 3], 5);
|
9264 | * // => [1, 2, 3]
|
9265 | *
|
9266 | * _.takeRight([1, 2, 3], 0);
|
9267 | * // => []
|
9268 | */
|
9269 | function takeRight(array, n, guard) {
|
9270 | var length = array ? array.length : 0;
|
9271 | if (!length) {
|
9272 | return [];
|
9273 | }
|
9274 | if (guard ? isIterateeCall(array, n, guard) : n == null) {
|
9275 | n = 1;
|
9276 | }
|
9277 | n = length - (+n || 0);
|
9278 | return baseSlice(array, n < 0 ? 0 : n);
|
9279 | }
|
9280 |
|
9281 | /**
|
9282 | * Creates a slice of `array` with elements taken from the end. Elements are
|
9283 | * taken until `predicate` returns falsey. The predicate is bound to `thisArg`
|
9284 | * and invoked with three arguments: (value, index, array).
|
9285 | *
|
9286 | * If a property name is provided for `predicate` the created `_.property`
|
9287 | * style callback returns the property value of the given element.
|
9288 | *
|
9289 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
9290 | * style callback returns `true` for elements that have a matching property
|
9291 | * value, else `false`.
|
9292 | *
|
9293 | * If an object is provided for `predicate` the created `_.matches` style
|
9294 | * callback returns `true` for elements that have the properties of the given
|
9295 | * object, else `false`.
|
9296 | *
|
9297 | * @static
|
9298 | * @memberOf _
|
9299 | * @category Array
|
9300 | * @param {Array} array The array to query.
|
9301 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
9302 | * per iteration.
|
9303 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
9304 | * @returns {Array} Returns the slice of `array`.
|
9305 | * @example
|
9306 | *
|
9307 | * _.takeRightWhile([1, 2, 3], function(n) {
|
9308 | * return n > 1;
|
9309 | * });
|
9310 | * // => [2, 3]
|
9311 | *
|
9312 | * var users = [
|
9313 | * { 'user': 'barney', 'active': true },
|
9314 | * { 'user': 'fred', 'active': false },
|
9315 | * { 'user': 'pebbles', 'active': false }
|
9316 | * ];
|
9317 | *
|
9318 | * // using the `_.matches` callback shorthand
|
9319 | * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
|
9320 | * // => ['pebbles']
|
9321 | *
|
9322 | * // using the `_.matchesProperty` callback shorthand
|
9323 | * _.pluck(_.takeRightWhile(users, 'active', false), 'user');
|
9324 | * // => ['fred', 'pebbles']
|
9325 | *
|
9326 | * // using the `_.property` callback shorthand
|
9327 | * _.pluck(_.takeRightWhile(users, 'active'), 'user');
|
9328 | * // => []
|
9329 | */
|
9330 | function takeRightWhile(array, predicate, thisArg) {
|
9331 | return (array && array.length)
|
9332 | ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true)
|
9333 | : [];
|
9334 | }
|
9335 |
|
9336 | /**
|
9337 | * Creates a slice of `array` with elements taken from the beginning. Elements
|
9338 | * are taken until `predicate` returns falsey. The predicate is bound to
|
9339 | * `thisArg` and invoked with three arguments: (value, index, array).
|
9340 | *
|
9341 | * If a property name is provided for `predicate` the created `_.property`
|
9342 | * style callback returns the property value of the given element.
|
9343 | *
|
9344 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
9345 | * style callback returns `true` for elements that have a matching property
|
9346 | * value, else `false`.
|
9347 | *
|
9348 | * If an object is provided for `predicate` the created `_.matches` style
|
9349 | * callback returns `true` for elements that have the properties of the given
|
9350 | * object, else `false`.
|
9351 | *
|
9352 | * @static
|
9353 | * @memberOf _
|
9354 | * @category Array
|
9355 | * @param {Array} array The array to query.
|
9356 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
9357 | * per iteration.
|
9358 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
9359 | * @returns {Array} Returns the slice of `array`.
|
9360 | * @example
|
9361 | *
|
9362 | * _.takeWhile([1, 2, 3], function(n) {
|
9363 | * return n < 3;
|
9364 | * });
|
9365 | * // => [1, 2]
|
9366 | *
|
9367 | * var users = [
|
9368 | * { 'user': 'barney', 'active': false },
|
9369 | * { 'user': 'fred', 'active': false},
|
9370 | * { 'user': 'pebbles', 'active': true }
|
9371 | * ];
|
9372 | *
|
9373 | * // using the `_.matches` callback shorthand
|
9374 | * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
|
9375 | * // => ['barney']
|
9376 | *
|
9377 | * // using the `_.matchesProperty` callback shorthand
|
9378 | * _.pluck(_.takeWhile(users, 'active', false), 'user');
|
9379 | * // => ['barney', 'fred']
|
9380 | *
|
9381 | * // using the `_.property` callback shorthand
|
9382 | * _.pluck(_.takeWhile(users, 'active'), 'user');
|
9383 | * // => []
|
9384 | */
|
9385 | function takeWhile(array, predicate, thisArg) {
|
9386 | return (array && array.length)
|
9387 | ? baseWhile(array, getCallback(predicate, thisArg, 3))
|
9388 | : [];
|
9389 | }
|
9390 |
|
9391 | /**
|
9392 | * Creates an array of unique values, in order, from all of the provided arrays
|
9393 | * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
|
9394 | * for equality comparisons.
|
9395 | *
|
9396 | * @static
|
9397 | * @memberOf _
|
9398 | * @category Array
|
9399 | * @param {...Array} [arrays] The arrays to inspect.
|
9400 | * @returns {Array} Returns the new array of combined values.
|
9401 | * @example
|
9402 | *
|
9403 | * _.union([1, 2], [4, 2], [2, 1]);
|
9404 | * // => [1, 2, 4]
|
9405 | */
|
9406 | var union = restParam(function(arrays) {
|
9407 | return baseUniq(baseFlatten(arrays, false, true));
|
9408 | });
|
9409 |
|
9410 | /**
|
9411 | * Creates a duplicate-free version of an array, using
|
9412 | * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
|
9413 | * for equality comparisons, in which only the first occurence of each element
|
9414 | * is kept. Providing `true` for `isSorted` performs a faster search algorithm
|
9415 | * for sorted arrays. If an iteratee function is provided it is invoked for
|
9416 | * each element in the array to generate the criterion by which uniqueness
|
9417 | * is computed. The `iteratee` is bound to `thisArg` and invoked with three
|
9418 | * arguments: (value, index, array).
|
9419 | *
|
9420 | * If a property name is provided for `iteratee` the created `_.property`
|
9421 | * style callback returns the property value of the given element.
|
9422 | *
|
9423 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
9424 | * style callback returns `true` for elements that have a matching property
|
9425 | * value, else `false`.
|
9426 | *
|
9427 | * If an object is provided for `iteratee` the created `_.matches` style
|
9428 | * callback returns `true` for elements that have the properties of the given
|
9429 | * object, else `false`.
|
9430 | *
|
9431 | * @static
|
9432 | * @memberOf _
|
9433 | * @alias unique
|
9434 | * @category Array
|
9435 | * @param {Array} array The array to inspect.
|
9436 | * @param {boolean} [isSorted] Specify the array is sorted.
|
9437 | * @param {Function|Object|string} [iteratee] The function invoked per iteration.
|
9438 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
9439 | * @returns {Array} Returns the new duplicate-value-free array.
|
9440 | * @example
|
9441 | *
|
9442 | * _.uniq([2, 1, 2]);
|
9443 | * // => [2, 1]
|
9444 | *
|
9445 | * // using `isSorted`
|
9446 | * _.uniq([1, 1, 2], true);
|
9447 | * // => [1, 2]
|
9448 | *
|
9449 | * // using an iteratee function
|
9450 | * _.uniq([1, 2.5, 1.5, 2], function(n) {
|
9451 | * return this.floor(n);
|
9452 | * }, Math);
|
9453 | * // => [1, 2.5]
|
9454 | *
|
9455 | * // using the `_.property` callback shorthand
|
9456 | * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
|
9457 | * // => [{ 'x': 1 }, { 'x': 2 }]
|
9458 | */
|
9459 | function uniq(array, isSorted, iteratee, thisArg) {
|
9460 | var length = array ? array.length : 0;
|
9461 | if (!length) {
|
9462 | return [];
|
9463 | }
|
9464 | if (isSorted != null && typeof isSorted != 'boolean') {
|
9465 | thisArg = iteratee;
|
9466 | iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted;
|
9467 | isSorted = false;
|
9468 | }
|
9469 | var callback = getCallback();
|
9470 | if (!(iteratee == null && callback === baseCallback)) {
|
9471 | iteratee = callback(iteratee, thisArg, 3);
|
9472 | }
|
9473 | return (isSorted && getIndexOf() == baseIndexOf)
|
9474 | ? sortedUniq(array, iteratee)
|
9475 | : baseUniq(array, iteratee);
|
9476 | }
|
9477 |
|
9478 | /**
|
9479 | * This method is like `_.zip` except that it accepts an array of grouped
|
9480 | * elements and creates an array regrouping the elements to their pre-zip
|
9481 | * configuration.
|
9482 | *
|
9483 | * @static
|
9484 | * @memberOf _
|
9485 | * @category Array
|
9486 | * @param {Array} array The array of grouped elements to process.
|
9487 | * @returns {Array} Returns the new array of regrouped elements.
|
9488 | * @example
|
9489 | *
|
9490 | * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
|
9491 | * // => [['fred', 30, true], ['barney', 40, false]]
|
9492 | *
|
9493 | * _.unzip(zipped);
|
9494 | * // => [['fred', 'barney'], [30, 40], [true, false]]
|
9495 | */
|
9496 | function unzip(array) {
|
9497 | if (!(array && array.length)) {
|
9498 | return [];
|
9499 | }
|
9500 | var index = -1,
|
9501 | length = 0;
|
9502 |
|
9503 | array = arrayFilter(array, function(group) {
|
9504 | if (isArrayLike(group)) {
|
9505 | length = nativeMax(group.length, length);
|
9506 | return true;
|
9507 | }
|
9508 | });
|
9509 | var result = Array(length);
|
9510 | while (++index < length) {
|
9511 | result[index] = arrayMap(array, baseProperty(index));
|
9512 | }
|
9513 | return result;
|
9514 | }
|
9515 |
|
9516 | /**
|
9517 | * This method is like `_.unzip` except that it accepts an iteratee to specify
|
9518 | * how regrouped values should be combined. The `iteratee` is bound to `thisArg`
|
9519 | * and invoked with four arguments: (accumulator, value, index, group).
|
9520 | *
|
9521 | * @static
|
9522 | * @memberOf _
|
9523 | * @category Array
|
9524 | * @param {Array} array The array of grouped elements to process.
|
9525 | * @param {Function} [iteratee] The function to combine regrouped values.
|
9526 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
9527 | * @returns {Array} Returns the new array of regrouped elements.
|
9528 | * @example
|
9529 | *
|
9530 | * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
|
9531 | * // => [[1, 10, 100], [2, 20, 200]]
|
9532 | *
|
9533 | * _.unzipWith(zipped, _.add);
|
9534 | * // => [3, 30, 300]
|
9535 | */
|
9536 | function unzipWith(array, iteratee, thisArg) {
|
9537 | var length = array ? array.length : 0;
|
9538 | if (!length) {
|
9539 | return [];
|
9540 | }
|
9541 | var result = unzip(array);
|
9542 | if (iteratee == null) {
|
9543 | return result;
|
9544 | }
|
9545 | iteratee = bindCallback(iteratee, thisArg, 4);
|
9546 | return arrayMap(result, function(group) {
|
9547 | return arrayReduce(group, iteratee, undefined, true);
|
9548 | });
|
9549 | }
|
9550 |
|
9551 | /**
|
9552 | * Creates an array excluding all provided values using
|
9553 | * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
|
9554 | * for equality comparisons.
|
9555 | *
|
9556 | * @static
|
9557 | * @memberOf _
|
9558 | * @category Array
|
9559 | * @param {Array} array The array to filter.
|
9560 | * @param {...*} [values] The values to exclude.
|
9561 | * @returns {Array} Returns the new array of filtered values.
|
9562 | * @example
|
9563 | *
|
9564 | * _.without([1, 2, 1, 3], 1, 2);
|
9565 | * // => [3]
|
9566 | */
|
9567 | var without = restParam(function(array, values) {
|
9568 | return isArrayLike(array)
|
9569 | ? baseDifference(array, values)
|
9570 | : [];
|
9571 | });
|
9572 |
|
9573 | /**
|
9574 | * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
|
9575 | * of the provided arrays.
|
9576 | *
|
9577 | * @static
|
9578 | * @memberOf _
|
9579 | * @category Array
|
9580 | * @param {...Array} [arrays] The arrays to inspect.
|
9581 | * @returns {Array} Returns the new array of values.
|
9582 | * @example
|
9583 | *
|
9584 | * _.xor([1, 2], [4, 2]);
|
9585 | * // => [1, 4]
|
9586 | */
|
9587 | function xor() {
|
9588 | var index = -1,
|
9589 | length = arguments.length;
|
9590 |
|
9591 | while (++index < length) {
|
9592 | var array = arguments[index];
|
9593 | if (isArrayLike(array)) {
|
9594 | var result = result
|
9595 | ? arrayPush(baseDifference(result, array), baseDifference(array, result))
|
9596 | : array;
|
9597 | }
|
9598 | }
|
9599 | return result ? baseUniq(result) : [];
|
9600 | }
|
9601 |
|
9602 | /**
|
9603 | * Creates an array of grouped elements, the first of which contains the first
|
9604 | * elements of the given arrays, the second of which contains the second elements
|
9605 | * of the given arrays, and so on.
|
9606 | *
|
9607 | * @static
|
9608 | * @memberOf _
|
9609 | * @category Array
|
9610 | * @param {...Array} [arrays] The arrays to process.
|
9611 | * @returns {Array} Returns the new array of grouped elements.
|
9612 | * @example
|
9613 | *
|
9614 | * _.zip(['fred', 'barney'], [30, 40], [true, false]);
|
9615 | * // => [['fred', 30, true], ['barney', 40, false]]
|
9616 | */
|
9617 | var zip = restParam(unzip);
|
9618 |
|
9619 | /**
|
9620 | * The inverse of `_.pairs`; this method returns an object composed from arrays
|
9621 | * of property names and values. Provide either a single two dimensional array,
|
9622 | * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
|
9623 | * and one of corresponding values.
|
9624 | *
|
9625 | * @static
|
9626 | * @memberOf _
|
9627 | * @alias object
|
9628 | * @category Array
|
9629 | * @param {Array} props The property names.
|
9630 | * @param {Array} [values=[]] The property values.
|
9631 | * @returns {Object} Returns the new object.
|
9632 | * @example
|
9633 | *
|
9634 | * _.zipObject([['fred', 30], ['barney', 40]]);
|
9635 | * // => { 'fred': 30, 'barney': 40 }
|
9636 | *
|
9637 | * _.zipObject(['fred', 'barney'], [30, 40]);
|
9638 | * // => { 'fred': 30, 'barney': 40 }
|
9639 | */
|
9640 | function zipObject(props, values) {
|
9641 | var index = -1,
|
9642 | length = props ? props.length : 0,
|
9643 | result = {};
|
9644 |
|
9645 | if (length && !values && !isArray(props[0])) {
|
9646 | values = [];
|
9647 | }
|
9648 | while (++index < length) {
|
9649 | var key = props[index];
|
9650 | if (values) {
|
9651 | result[key] = values[index];
|
9652 | } else if (key) {
|
9653 | result[key[0]] = key[1];
|
9654 | }
|
9655 | }
|
9656 | return result;
|
9657 | }
|
9658 |
|
9659 | /**
|
9660 | * This method is like `_.zip` except that it accepts an iteratee to specify
|
9661 | * how grouped values should be combined. The `iteratee` is bound to `thisArg`
|
9662 | * and invoked with four arguments: (accumulator, value, index, group).
|
9663 | *
|
9664 | * @static
|
9665 | * @memberOf _
|
9666 | * @category Array
|
9667 | * @param {...Array} [arrays] The arrays to process.
|
9668 | * @param {Function} [iteratee] The function to combine grouped values.
|
9669 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
9670 | * @returns {Array} Returns the new array of grouped elements.
|
9671 | * @example
|
9672 | *
|
9673 | * _.zipWith([1, 2], [10, 20], [100, 200], _.add);
|
9674 | * // => [111, 222]
|
9675 | */
|
9676 | var zipWith = restParam(function(arrays) {
|
9677 | var length = arrays.length,
|
9678 | iteratee = length > 2 ? arrays[length - 2] : undefined,
|
9679 | thisArg = length > 1 ? arrays[length - 1] : undefined;
|
9680 |
|
9681 | if (length > 2 && typeof iteratee == 'function') {
|
9682 | length -= 2;
|
9683 | } else {
|
9684 | iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined;
|
9685 | thisArg = undefined;
|
9686 | }
|
9687 | arrays.length = length;
|
9688 | return unzipWith(arrays, iteratee, thisArg);
|
9689 | });
|
9690 |
|
9691 | /*------------------------------------------------------------------------*/
|
9692 |
|
9693 | /**
|
9694 | * Creates a `lodash` object that wraps `value` with explicit method
|
9695 | * chaining enabled.
|
9696 | *
|
9697 | * @static
|
9698 | * @memberOf _
|
9699 | * @category Chain
|
9700 | * @param {*} value The value to wrap.
|
9701 | * @returns {Object} Returns the new `lodash` wrapper instance.
|
9702 | * @example
|
9703 | *
|
9704 | * var users = [
|
9705 | * { 'user': 'barney', 'age': 36 },
|
9706 | * { 'user': 'fred', 'age': 40 },
|
9707 | * { 'user': 'pebbles', 'age': 1 }
|
9708 | * ];
|
9709 | *
|
9710 | * var youngest = _.chain(users)
|
9711 | * .sortBy('age')
|
9712 | * .map(function(chr) {
|
9713 | * return chr.user + ' is ' + chr.age;
|
9714 | * })
|
9715 | * .first()
|
9716 | * .value();
|
9717 | * // => 'pebbles is 1'
|
9718 | */
|
9719 | function chain(value) {
|
9720 | var result = lodash(value);
|
9721 | result.__chain__ = true;
|
9722 | return result;
|
9723 | }
|
9724 |
|
9725 | /**
|
9726 | * This method invokes `interceptor` and returns `value`. The interceptor is
|
9727 | * bound to `thisArg` and invoked with one argument; (value). The purpose of
|
9728 | * this method is to "tap into" a method chain in order to perform operations
|
9729 | * on intermediate results within the chain.
|
9730 | *
|
9731 | * @static
|
9732 | * @memberOf _
|
9733 | * @category Chain
|
9734 | * @param {*} value The value to provide to `interceptor`.
|
9735 | * @param {Function} interceptor The function to invoke.
|
9736 | * @param {*} [thisArg] The `this` binding of `interceptor`.
|
9737 | * @returns {*} Returns `value`.
|
9738 | * @example
|
9739 | *
|
9740 | * _([1, 2, 3])
|
9741 | * .tap(function(array) {
|
9742 | * array.pop();
|
9743 | * })
|
9744 | * .reverse()
|
9745 | * .value();
|
9746 | * // => [2, 1]
|
9747 | */
|
9748 | function tap(value, interceptor, thisArg) {
|
9749 | interceptor.call(thisArg, value);
|
9750 | return value;
|
9751 | }
|
9752 |
|
9753 | /**
|
9754 | * This method is like `_.tap` except that it returns the result of `interceptor`.
|
9755 | *
|
9756 | * @static
|
9757 | * @memberOf _
|
9758 | * @category Chain
|
9759 | * @param {*} value The value to provide to `interceptor`.
|
9760 | * @param {Function} interceptor The function to invoke.
|
9761 | * @param {*} [thisArg] The `this` binding of `interceptor`.
|
9762 | * @returns {*} Returns the result of `interceptor`.
|
9763 | * @example
|
9764 | *
|
9765 | * _(' abc ')
|
9766 | * .chain()
|
9767 | * .trim()
|
9768 | * .thru(function(value) {
|
9769 | * return [value];
|
9770 | * })
|
9771 | * .value();
|
9772 | * // => ['abc']
|
9773 | */
|
9774 | function thru(value, interceptor, thisArg) {
|
9775 | return interceptor.call(thisArg, value);
|
9776 | }
|
9777 |
|
9778 | /**
|
9779 | * Enables explicit method chaining on the wrapper object.
|
9780 | *
|
9781 | * @name chain
|
9782 | * @memberOf _
|
9783 | * @category Chain
|
9784 | * @returns {Object} Returns the new `lodash` wrapper instance.
|
9785 | * @example
|
9786 | *
|
9787 | * var users = [
|
9788 | * { 'user': 'barney', 'age': 36 },
|
9789 | * { 'user': 'fred', 'age': 40 }
|
9790 | * ];
|
9791 | *
|
9792 | * // without explicit chaining
|
9793 | * _(users).first();
|
9794 | * // => { 'user': 'barney', 'age': 36 }
|
9795 | *
|
9796 | * // with explicit chaining
|
9797 | * _(users).chain()
|
9798 | * .first()
|
9799 | * .pick('user')
|
9800 | * .value();
|
9801 | * // => { 'user': 'barney' }
|
9802 | */
|
9803 | function wrapperChain() {
|
9804 | return chain(this);
|
9805 | }
|
9806 |
|
9807 | /**
|
9808 | * Executes the chained sequence and returns the wrapped result.
|
9809 | *
|
9810 | * @name commit
|
9811 | * @memberOf _
|
9812 | * @category Chain
|
9813 | * @returns {Object} Returns the new `lodash` wrapper instance.
|
9814 | * @example
|
9815 | *
|
9816 | * var array = [1, 2];
|
9817 | * var wrapped = _(array).push(3);
|
9818 | *
|
9819 | * console.log(array);
|
9820 | * // => [1, 2]
|
9821 | *
|
9822 | * wrapped = wrapped.commit();
|
9823 | * console.log(array);
|
9824 | * // => [1, 2, 3]
|
9825 | *
|
9826 | * wrapped.last();
|
9827 | * // => 3
|
9828 | *
|
9829 | * console.log(array);
|
9830 | * // => [1, 2, 3]
|
9831 | */
|
9832 | function wrapperCommit() {
|
9833 | return new LodashWrapper(this.value(), this.__chain__);
|
9834 | }
|
9835 |
|
9836 | /**
|
9837 | * Creates a new array joining a wrapped array with any additional arrays
|
9838 | * and/or values.
|
9839 | *
|
9840 | * @name concat
|
9841 | * @memberOf _
|
9842 | * @category Chain
|
9843 | * @param {...*} [values] The values to concatenate.
|
9844 | * @returns {Array} Returns the new concatenated array.
|
9845 | * @example
|
9846 | *
|
9847 | * var array = [1];
|
9848 | * var wrapped = _(array).concat(2, [3], [[4]]);
|
9849 | *
|
9850 | * console.log(wrapped.value());
|
9851 | * // => [1, 2, 3, [4]]
|
9852 | *
|
9853 | * console.log(array);
|
9854 | * // => [1]
|
9855 | */
|
9856 | var wrapperConcat = restParam(function(values) {
|
9857 | values = baseFlatten(values);
|
9858 | return this.thru(function(array) {
|
9859 | return arrayConcat(isArray(array) ? array : [toObject(array)], values);
|
9860 | });
|
9861 | });
|
9862 |
|
9863 | /**
|
9864 | * Creates a clone of the chained sequence planting `value` as the wrapped value.
|
9865 | *
|
9866 | * @name plant
|
9867 | * @memberOf _
|
9868 | * @category Chain
|
9869 | * @returns {Object} Returns the new `lodash` wrapper instance.
|
9870 | * @example
|
9871 | *
|
9872 | * var array = [1, 2];
|
9873 | * var wrapped = _(array).map(function(value) {
|
9874 | * return Math.pow(value, 2);
|
9875 | * });
|
9876 | *
|
9877 | * var other = [3, 4];
|
9878 | * var otherWrapped = wrapped.plant(other);
|
9879 | *
|
9880 | * otherWrapped.value();
|
9881 | * // => [9, 16]
|
9882 | *
|
9883 | * wrapped.value();
|
9884 | * // => [1, 4]
|
9885 | */
|
9886 | function wrapperPlant(value) {
|
9887 | var result,
|
9888 | parent = this;
|
9889 |
|
9890 | while (parent instanceof baseLodash) {
|
9891 | var clone = wrapperClone(parent);
|
9892 | if (result) {
|
9893 | previous.__wrapped__ = clone;
|
9894 | } else {
|
9895 | result = clone;
|
9896 | }
|
9897 | var previous = clone;
|
9898 | parent = parent.__wrapped__;
|
9899 | }
|
9900 | previous.__wrapped__ = value;
|
9901 | return result;
|
9902 | }
|
9903 |
|
9904 | /**
|
9905 | * Reverses the wrapped array so the first element becomes the last, the
|
9906 | * second element becomes the second to last, and so on.
|
9907 | *
|
9908 | * **Note:** This method mutates the wrapped array.
|
9909 | *
|
9910 | * @name reverse
|
9911 | * @memberOf _
|
9912 | * @category Chain
|
9913 | * @returns {Object} Returns the new reversed `lodash` wrapper instance.
|
9914 | * @example
|
9915 | *
|
9916 | * var array = [1, 2, 3];
|
9917 | *
|
9918 | * _(array).reverse().value()
|
9919 | * // => [3, 2, 1]
|
9920 | *
|
9921 | * console.log(array);
|
9922 | * // => [3, 2, 1]
|
9923 | */
|
9924 | function wrapperReverse() {
|
9925 | var value = this.__wrapped__;
|
9926 |
|
9927 | var interceptor = function(value) {
|
9928 | return (wrapped && wrapped.__dir__ < 0) ? value : value.reverse();
|
9929 | };
|
9930 | if (value instanceof LazyWrapper) {
|
9931 | var wrapped = value;
|
9932 | if (this.__actions__.length) {
|
9933 | wrapped = new LazyWrapper(this);
|
9934 | }
|
9935 | wrapped = wrapped.reverse();
|
9936 | wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
|
9937 | return new LodashWrapper(wrapped, this.__chain__);
|
9938 | }
|
9939 | return this.thru(interceptor);
|
9940 | }
|
9941 |
|
9942 | /**
|
9943 | * Produces the result of coercing the unwrapped value to a string.
|
9944 | *
|
9945 | * @name toString
|
9946 | * @memberOf _
|
9947 | * @category Chain
|
9948 | * @returns {string} Returns the coerced string value.
|
9949 | * @example
|
9950 | *
|
9951 | * _([1, 2, 3]).toString();
|
9952 | * // => '1,2,3'
|
9953 | */
|
9954 | function wrapperToString() {
|
9955 | return (this.value() + '');
|
9956 | }
|
9957 |
|
9958 | /**
|
9959 | * Executes the chained sequence to extract the unwrapped value.
|
9960 | *
|
9961 | * @name value
|
9962 | * @memberOf _
|
9963 | * @alias run, toJSON, valueOf
|
9964 | * @category Chain
|
9965 | * @returns {*} Returns the resolved unwrapped value.
|
9966 | * @example
|
9967 | *
|
9968 | * _([1, 2, 3]).value();
|
9969 | * // => [1, 2, 3]
|
9970 | */
|
9971 | function wrapperValue() {
|
9972 | return baseWrapperValue(this.__wrapped__, this.__actions__);
|
9973 | }
|
9974 |
|
9975 | /*------------------------------------------------------------------------*/
|
9976 |
|
9977 | /**
|
9978 | * Creates an array of elements corresponding to the given keys, or indexes,
|
9979 | * of `collection`. Keys may be specified as individual arguments or as arrays
|
9980 | * of keys.
|
9981 | *
|
9982 | * @static
|
9983 | * @memberOf _
|
9984 | * @category Collection
|
9985 | * @param {Array|Object|string} collection The collection to iterate over.
|
9986 | * @param {...(number|number[]|string|string[])} [props] The property names
|
9987 | * or indexes of elements to pick, specified individually or in arrays.
|
9988 | * @returns {Array} Returns the new array of picked elements.
|
9989 | * @example
|
9990 | *
|
9991 | * _.at(['a', 'b', 'c'], [0, 2]);
|
9992 | * // => ['a', 'c']
|
9993 | *
|
9994 | * _.at(['barney', 'fred', 'pebbles'], 0, 2);
|
9995 | * // => ['barney', 'pebbles']
|
9996 | */
|
9997 | var at = restParam(function(collection, props) {
|
9998 | return baseAt(collection, baseFlatten(props));
|
9999 | });
|
10000 |
|
10001 | /**
|
10002 | * Creates an object composed of keys generated from the results of running
|
10003 | * each element of `collection` through `iteratee`. The corresponding value
|
10004 | * of each key is the number of times the key was returned by `iteratee`.
|
10005 | * The `iteratee` is bound to `thisArg` and invoked with three arguments:
|
10006 | * (value, index|key, collection).
|
10007 | *
|
10008 | * If a property name is provided for `iteratee` the created `_.property`
|
10009 | * style callback returns the property value of the given element.
|
10010 | *
|
10011 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10012 | * style callback returns `true` for elements that have a matching property
|
10013 | * value, else `false`.
|
10014 | *
|
10015 | * If an object is provided for `iteratee` the created `_.matches` style
|
10016 | * callback returns `true` for elements that have the properties of the given
|
10017 | * object, else `false`.
|
10018 | *
|
10019 | * @static
|
10020 | * @memberOf _
|
10021 | * @category Collection
|
10022 | * @param {Array|Object|string} collection The collection to iterate over.
|
10023 | * @param {Function|Object|string} [iteratee=_.identity] The function invoked
|
10024 | * per iteration.
|
10025 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
10026 | * @returns {Object} Returns the composed aggregate object.
|
10027 | * @example
|
10028 | *
|
10029 | * _.countBy([4.3, 6.1, 6.4], function(n) {
|
10030 | * return Math.floor(n);
|
10031 | * });
|
10032 | * // => { '4': 1, '6': 2 }
|
10033 | *
|
10034 | * _.countBy([4.3, 6.1, 6.4], function(n) {
|
10035 | * return this.floor(n);
|
10036 | * }, Math);
|
10037 | * // => { '4': 1, '6': 2 }
|
10038 | *
|
10039 | * _.countBy(['one', 'two', 'three'], 'length');
|
10040 | * // => { '3': 2, '5': 1 }
|
10041 | */
|
10042 | var countBy = createAggregator(function(result, value, key) {
|
10043 | hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
|
10044 | });
|
10045 |
|
10046 | /**
|
10047 | * Checks if `predicate` returns truthy for **all** elements of `collection`.
|
10048 | * The predicate is bound to `thisArg` and invoked with three arguments:
|
10049 | * (value, index|key, collection).
|
10050 | *
|
10051 | * If a property name is provided for `predicate` the created `_.property`
|
10052 | * style callback returns the property value of the given element.
|
10053 | *
|
10054 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10055 | * style callback returns `true` for elements that have a matching property
|
10056 | * value, else `false`.
|
10057 | *
|
10058 | * If an object is provided for `predicate` the created `_.matches` style
|
10059 | * callback returns `true` for elements that have the properties of the given
|
10060 | * object, else `false`.
|
10061 | *
|
10062 | * @static
|
10063 | * @memberOf _
|
10064 | * @alias all
|
10065 | * @category Collection
|
10066 | * @param {Array|Object|string} collection The collection to iterate over.
|
10067 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
10068 | * per iteration.
|
10069 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
10070 | * @returns {boolean} Returns `true` if all elements pass the predicate check,
|
10071 | * else `false`.
|
10072 | * @example
|
10073 | *
|
10074 | * _.every([true, 1, null, 'yes'], Boolean);
|
10075 | * // => false
|
10076 | *
|
10077 | * var users = [
|
10078 | * { 'user': 'barney', 'active': false },
|
10079 | * { 'user': 'fred', 'active': false }
|
10080 | * ];
|
10081 | *
|
10082 | * // using the `_.matches` callback shorthand
|
10083 | * _.every(users, { 'user': 'barney', 'active': false });
|
10084 | * // => false
|
10085 | *
|
10086 | * // using the `_.matchesProperty` callback shorthand
|
10087 | * _.every(users, 'active', false);
|
10088 | * // => true
|
10089 | *
|
10090 | * // using the `_.property` callback shorthand
|
10091 | * _.every(users, 'active');
|
10092 | * // => false
|
10093 | */
|
10094 | function every(collection, predicate, thisArg) {
|
10095 | var func = isArray(collection) ? arrayEvery : baseEvery;
|
10096 | if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
|
10097 | predicate = undefined;
|
10098 | }
|
10099 | if (typeof predicate != 'function' || thisArg !== undefined) {
|
10100 | predicate = getCallback(predicate, thisArg, 3);
|
10101 | }
|
10102 | return func(collection, predicate);
|
10103 | }
|
10104 |
|
10105 | /**
|
10106 | * Iterates over elements of `collection`, returning an array of all elements
|
10107 | * `predicate` returns truthy for. The predicate is bound to `thisArg` and
|
10108 | * invoked with three arguments: (value, index|key, collection).
|
10109 | *
|
10110 | * If a property name is provided for `predicate` the created `_.property`
|
10111 | * style callback returns the property value of the given element.
|
10112 | *
|
10113 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10114 | * style callback returns `true` for elements that have a matching property
|
10115 | * value, else `false`.
|
10116 | *
|
10117 | * If an object is provided for `predicate` the created `_.matches` style
|
10118 | * callback returns `true` for elements that have the properties of the given
|
10119 | * object, else `false`.
|
10120 | *
|
10121 | * @static
|
10122 | * @memberOf _
|
10123 | * @alias select
|
10124 | * @category Collection
|
10125 | * @param {Array|Object|string} collection The collection to iterate over.
|
10126 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
10127 | * per iteration.
|
10128 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
10129 | * @returns {Array} Returns the new filtered array.
|
10130 | * @example
|
10131 | *
|
10132 | * _.filter([4, 5, 6], function(n) {
|
10133 | * return n % 2 == 0;
|
10134 | * });
|
10135 | * // => [4, 6]
|
10136 | *
|
10137 | * var users = [
|
10138 | * { 'user': 'barney', 'age': 36, 'active': true },
|
10139 | * { 'user': 'fred', 'age': 40, 'active': false }
|
10140 | * ];
|
10141 | *
|
10142 | * // using the `_.matches` callback shorthand
|
10143 | * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
|
10144 | * // => ['barney']
|
10145 | *
|
10146 | * // using the `_.matchesProperty` callback shorthand
|
10147 | * _.pluck(_.filter(users, 'active', false), 'user');
|
10148 | * // => ['fred']
|
10149 | *
|
10150 | * // using the `_.property` callback shorthand
|
10151 | * _.pluck(_.filter(users, 'active'), 'user');
|
10152 | * // => ['barney']
|
10153 | */
|
10154 | function filter(collection, predicate, thisArg) {
|
10155 | var func = isArray(collection) ? arrayFilter : baseFilter;
|
10156 | predicate = getCallback(predicate, thisArg, 3);
|
10157 | return func(collection, predicate);
|
10158 | }
|
10159 |
|
10160 | /**
|
10161 | * Iterates over elements of `collection`, returning the first element
|
10162 | * `predicate` returns truthy for. The predicate is bound to `thisArg` and
|
10163 | * invoked with three arguments: (value, index|key, collection).
|
10164 | *
|
10165 | * If a property name is provided for `predicate` the created `_.property`
|
10166 | * style callback returns the property value of the given element.
|
10167 | *
|
10168 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10169 | * style callback returns `true` for elements that have a matching property
|
10170 | * value, else `false`.
|
10171 | *
|
10172 | * If an object is provided for `predicate` the created `_.matches` style
|
10173 | * callback returns `true` for elements that have the properties of the given
|
10174 | * object, else `false`.
|
10175 | *
|
10176 | * @static
|
10177 | * @memberOf _
|
10178 | * @alias detect
|
10179 | * @category Collection
|
10180 | * @param {Array|Object|string} collection The collection to search.
|
10181 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
10182 | * per iteration.
|
10183 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
10184 | * @returns {*} Returns the matched element, else `undefined`.
|
10185 | * @example
|
10186 | *
|
10187 | * var users = [
|
10188 | * { 'user': 'barney', 'age': 36, 'active': true },
|
10189 | * { 'user': 'fred', 'age': 40, 'active': false },
|
10190 | * { 'user': 'pebbles', 'age': 1, 'active': true }
|
10191 | * ];
|
10192 | *
|
10193 | * _.result(_.find(users, function(chr) {
|
10194 | * return chr.age < 40;
|
10195 | * }), 'user');
|
10196 | * // => 'barney'
|
10197 | *
|
10198 | * // using the `_.matches` callback shorthand
|
10199 | * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
|
10200 | * // => 'pebbles'
|
10201 | *
|
10202 | * // using the `_.matchesProperty` callback shorthand
|
10203 | * _.result(_.find(users, 'active', false), 'user');
|
10204 | * // => 'fred'
|
10205 | *
|
10206 | * // using the `_.property` callback shorthand
|
10207 | * _.result(_.find(users, 'active'), 'user');
|
10208 | * // => 'barney'
|
10209 | */
|
10210 | var find = createFind(baseEach);
|
10211 |
|
10212 | /**
|
10213 | * This method is like `_.find` except that it iterates over elements of
|
10214 | * `collection` from right to left.
|
10215 | *
|
10216 | * @static
|
10217 | * @memberOf _
|
10218 | * @category Collection
|
10219 | * @param {Array|Object|string} collection The collection to search.
|
10220 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
10221 | * per iteration.
|
10222 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
10223 | * @returns {*} Returns the matched element, else `undefined`.
|
10224 | * @example
|
10225 | *
|
10226 | * _.findLast([1, 2, 3, 4], function(n) {
|
10227 | * return n % 2 == 1;
|
10228 | * });
|
10229 | * // => 3
|
10230 | */
|
10231 | var findLast = createFind(baseEachRight, true);
|
10232 |
|
10233 | /**
|
10234 | * Performs a deep comparison between each element in `collection` and the
|
10235 | * source object, returning the first element that has equivalent property
|
10236 | * values.
|
10237 | *
|
10238 | * **Note:** This method supports comparing arrays, booleans, `Date` objects,
|
10239 | * numbers, `Object` objects, regexes, and strings. Objects are compared by
|
10240 | * their own, not inherited, enumerable properties. For comparing a single
|
10241 | * own or inherited property value see `_.matchesProperty`.
|
10242 | *
|
10243 | * @static
|
10244 | * @memberOf _
|
10245 | * @category Collection
|
10246 | * @param {Array|Object|string} collection The collection to search.
|
10247 | * @param {Object} source The object of property values to match.
|
10248 | * @returns {*} Returns the matched element, else `undefined`.
|
10249 | * @example
|
10250 | *
|
10251 | * var users = [
|
10252 | * { 'user': 'barney', 'age': 36, 'active': true },
|
10253 | * { 'user': 'fred', 'age': 40, 'active': false }
|
10254 | * ];
|
10255 | *
|
10256 | * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
|
10257 | * // => 'barney'
|
10258 | *
|
10259 | * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
|
10260 | * // => 'fred'
|
10261 | */
|
10262 | function findWhere(collection, source) {
|
10263 | return find(collection, baseMatches(source));
|
10264 | }
|
10265 |
|
10266 | /**
|
10267 | * Iterates over elements of `collection` invoking `iteratee` for each element.
|
10268 | * The `iteratee` is bound to `thisArg` and invoked with three arguments:
|
10269 | * (value, index|key, collection). Iteratee functions may exit iteration early
|
10270 | * by explicitly returning `false`.
|
10271 | *
|
10272 | * **Note:** As with other "Collections" methods, objects with a "length" property
|
10273 | * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
|
10274 | * may be used for object iteration.
|
10275 | *
|
10276 | * @static
|
10277 | * @memberOf _
|
10278 | * @alias each
|
10279 | * @category Collection
|
10280 | * @param {Array|Object|string} collection The collection to iterate over.
|
10281 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
10282 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
10283 | * @returns {Array|Object|string} Returns `collection`.
|
10284 | * @example
|
10285 | *
|
10286 | * _([1, 2]).forEach(function(n) {
|
10287 | * console.log(n);
|
10288 | * }).value();
|
10289 | * // => logs each value from left to right and returns the array
|
10290 | *
|
10291 | * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
|
10292 | * console.log(n, key);
|
10293 | * });
|
10294 | * // => logs each value-key pair and returns the object (iteration order is not guaranteed)
|
10295 | */
|
10296 | var forEach = createForEach(arrayEach, baseEach);
|
10297 |
|
10298 | /**
|
10299 | * This method is like `_.forEach` except that it iterates over elements of
|
10300 | * `collection` from right to left.
|
10301 | *
|
10302 | * @static
|
10303 | * @memberOf _
|
10304 | * @alias eachRight
|
10305 | * @category Collection
|
10306 | * @param {Array|Object|string} collection The collection to iterate over.
|
10307 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
10308 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
10309 | * @returns {Array|Object|string} Returns `collection`.
|
10310 | * @example
|
10311 | *
|
10312 | * _([1, 2]).forEachRight(function(n) {
|
10313 | * console.log(n);
|
10314 | * }).value();
|
10315 | * // => logs each value from right to left and returns the array
|
10316 | */
|
10317 | var forEachRight = createForEach(arrayEachRight, baseEachRight);
|
10318 |
|
10319 | /**
|
10320 | * Creates an object composed of keys generated from the results of running
|
10321 | * each element of `collection` through `iteratee`. The corresponding value
|
10322 | * of each key is an array of the elements responsible for generating the key.
|
10323 | * The `iteratee` is bound to `thisArg` and invoked with three arguments:
|
10324 | * (value, index|key, collection).
|
10325 | *
|
10326 | * If a property name is provided for `iteratee` the created `_.property`
|
10327 | * style callback returns the property value of the given element.
|
10328 | *
|
10329 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10330 | * style callback returns `true` for elements that have a matching property
|
10331 | * value, else `false`.
|
10332 | *
|
10333 | * If an object is provided for `iteratee` the created `_.matches` style
|
10334 | * callback returns `true` for elements that have the properties of the given
|
10335 | * object, else `false`.
|
10336 | *
|
10337 | * @static
|
10338 | * @memberOf _
|
10339 | * @category Collection
|
10340 | * @param {Array|Object|string} collection The collection to iterate over.
|
10341 | * @param {Function|Object|string} [iteratee=_.identity] The function invoked
|
10342 | * per iteration.
|
10343 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
10344 | * @returns {Object} Returns the composed aggregate object.
|
10345 | * @example
|
10346 | *
|
10347 | * _.groupBy([4.2, 6.1, 6.4], function(n) {
|
10348 | * return Math.floor(n);
|
10349 | * });
|
10350 | * // => { '4': [4.2], '6': [6.1, 6.4] }
|
10351 | *
|
10352 | * _.groupBy([4.2, 6.1, 6.4], function(n) {
|
10353 | * return this.floor(n);
|
10354 | * }, Math);
|
10355 | * // => { '4': [4.2], '6': [6.1, 6.4] }
|
10356 | *
|
10357 | * // using the `_.property` callback shorthand
|
10358 | * _.groupBy(['one', 'two', 'three'], 'length');
|
10359 | * // => { '3': ['one', 'two'], '5': ['three'] }
|
10360 | */
|
10361 | var groupBy = createAggregator(function(result, value, key) {
|
10362 | if (hasOwnProperty.call(result, key)) {
|
10363 | result[key].push(value);
|
10364 | } else {
|
10365 | result[key] = [value];
|
10366 | }
|
10367 | });
|
10368 |
|
10369 | /**
|
10370 | * Checks if `value` is in `collection` using
|
10371 | * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
|
10372 | * for equality comparisons. If `fromIndex` is negative, it is used as the offset
|
10373 | * from the end of `collection`.
|
10374 | *
|
10375 | * @static
|
10376 | * @memberOf _
|
10377 | * @alias contains, include
|
10378 | * @category Collection
|
10379 | * @param {Array|Object|string} collection The collection to search.
|
10380 | * @param {*} target The value to search for.
|
10381 | * @param {number} [fromIndex=0] The index to search from.
|
10382 | * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
|
10383 | * @returns {boolean} Returns `true` if a matching element is found, else `false`.
|
10384 | * @example
|
10385 | *
|
10386 | * _.includes([1, 2, 3], 1);
|
10387 | * // => true
|
10388 | *
|
10389 | * _.includes([1, 2, 3], 1, 2);
|
10390 | * // => false
|
10391 | *
|
10392 | * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
|
10393 | * // => true
|
10394 | *
|
10395 | * _.includes('pebbles', 'eb');
|
10396 | * // => true
|
10397 | */
|
10398 | function includes(collection, target, fromIndex, guard) {
|
10399 | var length = collection ? getLength(collection) : 0;
|
10400 | if (!isLength(length)) {
|
10401 | collection = values(collection);
|
10402 | length = collection.length;
|
10403 | }
|
10404 | if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
|
10405 | fromIndex = 0;
|
10406 | } else {
|
10407 | fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
|
10408 | }
|
10409 | return (typeof collection == 'string' || !isArray(collection) && isString(collection))
|
10410 | ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
|
10411 | : (!!length && getIndexOf(collection, target, fromIndex) > -1);
|
10412 | }
|
10413 |
|
10414 | /**
|
10415 | * Creates an object composed of keys generated from the results of running
|
10416 | * each element of `collection` through `iteratee`. The corresponding value
|
10417 | * of each key is the last element responsible for generating the key. The
|
10418 | * iteratee function is bound to `thisArg` and invoked with three arguments:
|
10419 | * (value, index|key, collection).
|
10420 | *
|
10421 | * If a property name is provided for `iteratee` the created `_.property`
|
10422 | * style callback returns the property value of the given element.
|
10423 | *
|
10424 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10425 | * style callback returns `true` for elements that have a matching property
|
10426 | * value, else `false`.
|
10427 | *
|
10428 | * If an object is provided for `iteratee` the created `_.matches` style
|
10429 | * callback returns `true` for elements that have the properties of the given
|
10430 | * object, else `false`.
|
10431 | *
|
10432 | * @static
|
10433 | * @memberOf _
|
10434 | * @category Collection
|
10435 | * @param {Array|Object|string} collection The collection to iterate over.
|
10436 | * @param {Function|Object|string} [iteratee=_.identity] The function invoked
|
10437 | * per iteration.
|
10438 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
10439 | * @returns {Object} Returns the composed aggregate object.
|
10440 | * @example
|
10441 | *
|
10442 | * var keyData = [
|
10443 | * { 'dir': 'left', 'code': 97 },
|
10444 | * { 'dir': 'right', 'code': 100 }
|
10445 | * ];
|
10446 | *
|
10447 | * _.indexBy(keyData, 'dir');
|
10448 | * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
|
10449 | *
|
10450 | * _.indexBy(keyData, function(object) {
|
10451 | * return String.fromCharCode(object.code);
|
10452 | * });
|
10453 | * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
|
10454 | *
|
10455 | * _.indexBy(keyData, function(object) {
|
10456 | * return this.fromCharCode(object.code);
|
10457 | * }, String);
|
10458 | * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
|
10459 | */
|
10460 | var indexBy = createAggregator(function(result, value, key) {
|
10461 | result[key] = value;
|
10462 | });
|
10463 |
|
10464 | /**
|
10465 | * Invokes the method at `path` of each element in `collection`, returning
|
10466 | * an array of the results of each invoked method. Any additional arguments
|
10467 | * are provided to each invoked method. If `methodName` is a function it is
|
10468 | * invoked for, and `this` bound to, each element in `collection`.
|
10469 | *
|
10470 | * @static
|
10471 | * @memberOf _
|
10472 | * @category Collection
|
10473 | * @param {Array|Object|string} collection The collection to iterate over.
|
10474 | * @param {Array|Function|string} path The path of the method to invoke or
|
10475 | * the function invoked per iteration.
|
10476 | * @param {...*} [args] The arguments to invoke the method with.
|
10477 | * @returns {Array} Returns the array of results.
|
10478 | * @example
|
10479 | *
|
10480 | * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
|
10481 | * // => [[1, 5, 7], [1, 2, 3]]
|
10482 | *
|
10483 | * _.invoke([123, 456], String.prototype.split, '');
|
10484 | * // => [['1', '2', '3'], ['4', '5', '6']]
|
10485 | */
|
10486 | var invoke = restParam(function(collection, path, args) {
|
10487 | var index = -1,
|
10488 | isFunc = typeof path == 'function',
|
10489 | isProp = isKey(path),
|
10490 | result = isArrayLike(collection) ? Array(collection.length) : [];
|
10491 |
|
10492 | baseEach(collection, function(value) {
|
10493 | var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
|
10494 | result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
|
10495 | });
|
10496 | return result;
|
10497 | });
|
10498 |
|
10499 | /**
|
10500 | * Creates an array of values by running each element in `collection` through
|
10501 | * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
|
10502 | * arguments: (value, index|key, collection).
|
10503 | *
|
10504 | * If a property name is provided for `iteratee` the created `_.property`
|
10505 | * style callback returns the property value of the given element.
|
10506 | *
|
10507 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10508 | * style callback returns `true` for elements that have a matching property
|
10509 | * value, else `false`.
|
10510 | *
|
10511 | * If an object is provided for `iteratee` the created `_.matches` style
|
10512 | * callback returns `true` for elements that have the properties of the given
|
10513 | * object, else `false`.
|
10514 | *
|
10515 | * Many lodash methods are guarded to work as iteratees for methods like
|
10516 | * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
|
10517 | *
|
10518 | * The guarded methods are:
|
10519 | * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
|
10520 | * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
|
10521 | * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
|
10522 | * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
|
10523 | * `sum`, `uniq`, and `words`
|
10524 | *
|
10525 | * @static
|
10526 | * @memberOf _
|
10527 | * @alias collect
|
10528 | * @category Collection
|
10529 | * @param {Array|Object|string} collection The collection to iterate over.
|
10530 | * @param {Function|Object|string} [iteratee=_.identity] The function invoked
|
10531 | * per iteration.
|
10532 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
10533 | * @returns {Array} Returns the new mapped array.
|
10534 | * @example
|
10535 | *
|
10536 | * function timesThree(n) {
|
10537 | * return n * 3;
|
10538 | * }
|
10539 | *
|
10540 | * _.map([1, 2], timesThree);
|
10541 | * // => [3, 6]
|
10542 | *
|
10543 | * _.map({ 'a': 1, 'b': 2 }, timesThree);
|
10544 | * // => [3, 6] (iteration order is not guaranteed)
|
10545 | *
|
10546 | * var users = [
|
10547 | * { 'user': 'barney' },
|
10548 | * { 'user': 'fred' }
|
10549 | * ];
|
10550 | *
|
10551 | * // using the `_.property` callback shorthand
|
10552 | * _.map(users, 'user');
|
10553 | * // => ['barney', 'fred']
|
10554 | */
|
10555 | function map(collection, iteratee, thisArg) {
|
10556 | var func = isArray(collection) ? arrayMap : baseMap;
|
10557 | iteratee = getCallback(iteratee, thisArg, 3);
|
10558 | return func(collection, iteratee);
|
10559 | }
|
10560 |
|
10561 | /**
|
10562 | * Creates an array of elements split into two groups, the first of which
|
10563 | * contains elements `predicate` returns truthy for, while the second of which
|
10564 | * contains elements `predicate` returns falsey for. The predicate is bound
|
10565 | * to `thisArg` and invoked with three arguments: (value, index|key, collection).
|
10566 | *
|
10567 | * If a property name is provided for `predicate` the created `_.property`
|
10568 | * style callback returns the property value of the given element.
|
10569 | *
|
10570 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10571 | * style callback returns `true` for elements that have a matching property
|
10572 | * value, else `false`.
|
10573 | *
|
10574 | * If an object is provided for `predicate` the created `_.matches` style
|
10575 | * callback returns `true` for elements that have the properties of the given
|
10576 | * object, else `false`.
|
10577 | *
|
10578 | * @static
|
10579 | * @memberOf _
|
10580 | * @category Collection
|
10581 | * @param {Array|Object|string} collection The collection to iterate over.
|
10582 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
10583 | * per iteration.
|
10584 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
10585 | * @returns {Array} Returns the array of grouped elements.
|
10586 | * @example
|
10587 | *
|
10588 | * _.partition([1, 2, 3], function(n) {
|
10589 | * return n % 2;
|
10590 | * });
|
10591 | * // => [[1, 3], [2]]
|
10592 | *
|
10593 | * _.partition([1.2, 2.3, 3.4], function(n) {
|
10594 | * return this.floor(n) % 2;
|
10595 | * }, Math);
|
10596 | * // => [[1.2, 3.4], [2.3]]
|
10597 | *
|
10598 | * var users = [
|
10599 | * { 'user': 'barney', 'age': 36, 'active': false },
|
10600 | * { 'user': 'fred', 'age': 40, 'active': true },
|
10601 | * { 'user': 'pebbles', 'age': 1, 'active': false }
|
10602 | * ];
|
10603 | *
|
10604 | * var mapper = function(array) {
|
10605 | * return _.pluck(array, 'user');
|
10606 | * };
|
10607 | *
|
10608 | * // using the `_.matches` callback shorthand
|
10609 | * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
|
10610 | * // => [['pebbles'], ['barney', 'fred']]
|
10611 | *
|
10612 | * // using the `_.matchesProperty` callback shorthand
|
10613 | * _.map(_.partition(users, 'active', false), mapper);
|
10614 | * // => [['barney', 'pebbles'], ['fred']]
|
10615 | *
|
10616 | * // using the `_.property` callback shorthand
|
10617 | * _.map(_.partition(users, 'active'), mapper);
|
10618 | * // => [['fred'], ['barney', 'pebbles']]
|
10619 | */
|
10620 | var partition = createAggregator(function(result, value, key) {
|
10621 | result[key ? 0 : 1].push(value);
|
10622 | }, function() { return [[], []]; });
|
10623 |
|
10624 | /**
|
10625 | * Gets the property value of `path` from all elements in `collection`.
|
10626 | *
|
10627 | * @static
|
10628 | * @memberOf _
|
10629 | * @category Collection
|
10630 | * @param {Array|Object|string} collection The collection to iterate over.
|
10631 | * @param {Array|string} path The path of the property to pluck.
|
10632 | * @returns {Array} Returns the property values.
|
10633 | * @example
|
10634 | *
|
10635 | * var users = [
|
10636 | * { 'user': 'barney', 'age': 36 },
|
10637 | * { 'user': 'fred', 'age': 40 }
|
10638 | * ];
|
10639 | *
|
10640 | * _.pluck(users, 'user');
|
10641 | * // => ['barney', 'fred']
|
10642 | *
|
10643 | * var userIndex = _.indexBy(users, 'user');
|
10644 | * _.pluck(userIndex, 'age');
|
10645 | * // => [36, 40] (iteration order is not guaranteed)
|
10646 | */
|
10647 | function pluck(collection, path) {
|
10648 | return map(collection, property(path));
|
10649 | }
|
10650 |
|
10651 | /**
|
10652 | * Reduces `collection` to a value which is the accumulated result of running
|
10653 | * each element in `collection` through `iteratee`, where each successive
|
10654 | * invocation is supplied the return value of the previous. If `accumulator`
|
10655 | * is not provided the first element of `collection` is used as the initial
|
10656 | * value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
|
10657 | * (accumulator, value, index|key, collection).
|
10658 | *
|
10659 | * Many lodash methods are guarded to work as iteratees for methods like
|
10660 | * `_.reduce`, `_.reduceRight`, and `_.transform`.
|
10661 | *
|
10662 | * The guarded methods are:
|
10663 | * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
|
10664 | * and `sortByOrder`
|
10665 | *
|
10666 | * @static
|
10667 | * @memberOf _
|
10668 | * @alias foldl, inject
|
10669 | * @category Collection
|
10670 | * @param {Array|Object|string} collection The collection to iterate over.
|
10671 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
10672 | * @param {*} [accumulator] The initial value.
|
10673 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
10674 | * @returns {*} Returns the accumulated value.
|
10675 | * @example
|
10676 | *
|
10677 | * _.reduce([1, 2], function(total, n) {
|
10678 | * return total + n;
|
10679 | * });
|
10680 | * // => 3
|
10681 | *
|
10682 | * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
|
10683 | * result[key] = n * 3;
|
10684 | * return result;
|
10685 | * }, {});
|
10686 | * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
|
10687 | */
|
10688 | var reduce = createReduce(arrayReduce, baseEach);
|
10689 |
|
10690 | /**
|
10691 | * This method is like `_.reduce` except that it iterates over elements of
|
10692 | * `collection` from right to left.
|
10693 | *
|
10694 | * @static
|
10695 | * @memberOf _
|
10696 | * @alias foldr
|
10697 | * @category Collection
|
10698 | * @param {Array|Object|string} collection The collection to iterate over.
|
10699 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
10700 | * @param {*} [accumulator] The initial value.
|
10701 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
10702 | * @returns {*} Returns the accumulated value.
|
10703 | * @example
|
10704 | *
|
10705 | * var array = [[0, 1], [2, 3], [4, 5]];
|
10706 | *
|
10707 | * _.reduceRight(array, function(flattened, other) {
|
10708 | * return flattened.concat(other);
|
10709 | * }, []);
|
10710 | * // => [4, 5, 2, 3, 0, 1]
|
10711 | */
|
10712 | var reduceRight = createReduce(arrayReduceRight, baseEachRight);
|
10713 |
|
10714 | /**
|
10715 | * The opposite of `_.filter`; this method returns the elements of `collection`
|
10716 | * that `predicate` does **not** return truthy for.
|
10717 | *
|
10718 | * @static
|
10719 | * @memberOf _
|
10720 | * @category Collection
|
10721 | * @param {Array|Object|string} collection The collection to iterate over.
|
10722 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
10723 | * per iteration.
|
10724 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
10725 | * @returns {Array} Returns the new filtered array.
|
10726 | * @example
|
10727 | *
|
10728 | * _.reject([1, 2, 3, 4], function(n) {
|
10729 | * return n % 2 == 0;
|
10730 | * });
|
10731 | * // => [1, 3]
|
10732 | *
|
10733 | * var users = [
|
10734 | * { 'user': 'barney', 'age': 36, 'active': false },
|
10735 | * { 'user': 'fred', 'age': 40, 'active': true }
|
10736 | * ];
|
10737 | *
|
10738 | * // using the `_.matches` callback shorthand
|
10739 | * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
|
10740 | * // => ['barney']
|
10741 | *
|
10742 | * // using the `_.matchesProperty` callback shorthand
|
10743 | * _.pluck(_.reject(users, 'active', false), 'user');
|
10744 | * // => ['fred']
|
10745 | *
|
10746 | * // using the `_.property` callback shorthand
|
10747 | * _.pluck(_.reject(users, 'active'), 'user');
|
10748 | * // => ['barney']
|
10749 | */
|
10750 | function reject(collection, predicate, thisArg) {
|
10751 | var func = isArray(collection) ? arrayFilter : baseFilter;
|
10752 | predicate = getCallback(predicate, thisArg, 3);
|
10753 | return func(collection, function(value, index, collection) {
|
10754 | return !predicate(value, index, collection);
|
10755 | });
|
10756 | }
|
10757 |
|
10758 | /**
|
10759 | * Gets a random element or `n` random elements from a collection.
|
10760 | *
|
10761 | * @static
|
10762 | * @memberOf _
|
10763 | * @category Collection
|
10764 | * @param {Array|Object|string} collection The collection to sample.
|
10765 | * @param {number} [n] The number of elements to sample.
|
10766 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
10767 | * @returns {*} Returns the random sample(s).
|
10768 | * @example
|
10769 | *
|
10770 | * _.sample([1, 2, 3, 4]);
|
10771 | * // => 2
|
10772 | *
|
10773 | * _.sample([1, 2, 3, 4], 2);
|
10774 | * // => [3, 1]
|
10775 | */
|
10776 | function sample(collection, n, guard) {
|
10777 | if (guard ? isIterateeCall(collection, n, guard) : n == null) {
|
10778 | collection = toIterable(collection);
|
10779 | var length = collection.length;
|
10780 | return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
|
10781 | }
|
10782 | var index = -1,
|
10783 | result = toArray(collection),
|
10784 | length = result.length,
|
10785 | lastIndex = length - 1;
|
10786 |
|
10787 | n = nativeMin(n < 0 ? 0 : (+n || 0), length);
|
10788 | while (++index < n) {
|
10789 | var rand = baseRandom(index, lastIndex),
|
10790 | value = result[rand];
|
10791 |
|
10792 | result[rand] = result[index];
|
10793 | result[index] = value;
|
10794 | }
|
10795 | result.length = n;
|
10796 | return result;
|
10797 | }
|
10798 |
|
10799 | /**
|
10800 | * Creates an array of shuffled values, using a version of the
|
10801 | * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
|
10802 | *
|
10803 | * @static
|
10804 | * @memberOf _
|
10805 | * @category Collection
|
10806 | * @param {Array|Object|string} collection The collection to shuffle.
|
10807 | * @returns {Array} Returns the new shuffled array.
|
10808 | * @example
|
10809 | *
|
10810 | * _.shuffle([1, 2, 3, 4]);
|
10811 | * // => [4, 1, 3, 2]
|
10812 | */
|
10813 | function shuffle(collection) {
|
10814 | return sample(collection, POSITIVE_INFINITY);
|
10815 | }
|
10816 |
|
10817 | /**
|
10818 | * Gets the size of `collection` by returning its length for array-like
|
10819 | * values or the number of own enumerable properties for objects.
|
10820 | *
|
10821 | * @static
|
10822 | * @memberOf _
|
10823 | * @category Collection
|
10824 | * @param {Array|Object|string} collection The collection to inspect.
|
10825 | * @returns {number} Returns the size of `collection`.
|
10826 | * @example
|
10827 | *
|
10828 | * _.size([1, 2, 3]);
|
10829 | * // => 3
|
10830 | *
|
10831 | * _.size({ 'a': 1, 'b': 2 });
|
10832 | * // => 2
|
10833 | *
|
10834 | * _.size('pebbles');
|
10835 | * // => 7
|
10836 | */
|
10837 | function size(collection) {
|
10838 | var length = collection ? getLength(collection) : 0;
|
10839 | return isLength(length) ? length : keys(collection).length;
|
10840 | }
|
10841 |
|
10842 | /**
|
10843 | * Checks if `predicate` returns truthy for **any** element of `collection`.
|
10844 | * The function returns as soon as it finds a passing value and does not iterate
|
10845 | * over the entire collection. The predicate is bound to `thisArg` and invoked
|
10846 | * with three arguments: (value, index|key, collection).
|
10847 | *
|
10848 | * If a property name is provided for `predicate` the created `_.property`
|
10849 | * style callback returns the property value of the given element.
|
10850 | *
|
10851 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10852 | * style callback returns `true` for elements that have a matching property
|
10853 | * value, else `false`.
|
10854 | *
|
10855 | * If an object is provided for `predicate` the created `_.matches` style
|
10856 | * callback returns `true` for elements that have the properties of the given
|
10857 | * object, else `false`.
|
10858 | *
|
10859 | * @static
|
10860 | * @memberOf _
|
10861 | * @alias any
|
10862 | * @category Collection
|
10863 | * @param {Array|Object|string} collection The collection to iterate over.
|
10864 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
10865 | * per iteration.
|
10866 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
10867 | * @returns {boolean} Returns `true` if any element passes the predicate check,
|
10868 | * else `false`.
|
10869 | * @example
|
10870 | *
|
10871 | * _.some([null, 0, 'yes', false], Boolean);
|
10872 | * // => true
|
10873 | *
|
10874 | * var users = [
|
10875 | * { 'user': 'barney', 'active': true },
|
10876 | * { 'user': 'fred', 'active': false }
|
10877 | * ];
|
10878 | *
|
10879 | * // using the `_.matches` callback shorthand
|
10880 | * _.some(users, { 'user': 'barney', 'active': false });
|
10881 | * // => false
|
10882 | *
|
10883 | * // using the `_.matchesProperty` callback shorthand
|
10884 | * _.some(users, 'active', false);
|
10885 | * // => true
|
10886 | *
|
10887 | * // using the `_.property` callback shorthand
|
10888 | * _.some(users, 'active');
|
10889 | * // => true
|
10890 | */
|
10891 | function some(collection, predicate, thisArg) {
|
10892 | var func = isArray(collection) ? arraySome : baseSome;
|
10893 | if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
|
10894 | predicate = undefined;
|
10895 | }
|
10896 | if (typeof predicate != 'function' || thisArg !== undefined) {
|
10897 | predicate = getCallback(predicate, thisArg, 3);
|
10898 | }
|
10899 | return func(collection, predicate);
|
10900 | }
|
10901 |
|
10902 | /**
|
10903 | * Creates an array of elements, sorted in ascending order by the results of
|
10904 | * running each element in a collection through `iteratee`. This method performs
|
10905 | * a stable sort, that is, it preserves the original sort order of equal elements.
|
10906 | * The `iteratee` is bound to `thisArg` and invoked with three arguments:
|
10907 | * (value, index|key, collection).
|
10908 | *
|
10909 | * If a property name is provided for `iteratee` the created `_.property`
|
10910 | * style callback returns the property value of the given element.
|
10911 | *
|
10912 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
10913 | * style callback returns `true` for elements that have a matching property
|
10914 | * value, else `false`.
|
10915 | *
|
10916 | * If an object is provided for `iteratee` the created `_.matches` style
|
10917 | * callback returns `true` for elements that have the properties of the given
|
10918 | * object, else `false`.
|
10919 | *
|
10920 | * @static
|
10921 | * @memberOf _
|
10922 | * @category Collection
|
10923 | * @param {Array|Object|string} collection The collection to iterate over.
|
10924 | * @param {Function|Object|string} [iteratee=_.identity] The function invoked
|
10925 | * per iteration.
|
10926 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
10927 | * @returns {Array} Returns the new sorted array.
|
10928 | * @example
|
10929 | *
|
10930 | * _.sortBy([1, 2, 3], function(n) {
|
10931 | * return Math.sin(n);
|
10932 | * });
|
10933 | * // => [3, 1, 2]
|
10934 | *
|
10935 | * _.sortBy([1, 2, 3], function(n) {
|
10936 | * return this.sin(n);
|
10937 | * }, Math);
|
10938 | * // => [3, 1, 2]
|
10939 | *
|
10940 | * var users = [
|
10941 | * { 'user': 'fred' },
|
10942 | * { 'user': 'pebbles' },
|
10943 | * { 'user': 'barney' }
|
10944 | * ];
|
10945 | *
|
10946 | * // using the `_.property` callback shorthand
|
10947 | * _.pluck(_.sortBy(users, 'user'), 'user');
|
10948 | * // => ['barney', 'fred', 'pebbles']
|
10949 | */
|
10950 | function sortBy(collection, iteratee, thisArg) {
|
10951 | if (collection == null) {
|
10952 | return [];
|
10953 | }
|
10954 | if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
|
10955 | iteratee = undefined;
|
10956 | }
|
10957 | var index = -1;
|
10958 | iteratee = getCallback(iteratee, thisArg, 3);
|
10959 |
|
10960 | var result = baseMap(collection, function(value, key, collection) {
|
10961 | return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
|
10962 | });
|
10963 | return baseSortBy(result, compareAscending);
|
10964 | }
|
10965 |
|
10966 | /**
|
10967 | * This method is like `_.sortBy` except that it can sort by multiple iteratees
|
10968 | * or property names.
|
10969 | *
|
10970 | * If a property name is provided for an iteratee the created `_.property`
|
10971 | * style callback returns the property value of the given element.
|
10972 | *
|
10973 | * If an object is provided for an iteratee the created `_.matches` style
|
10974 | * callback returns `true` for elements that have the properties of the given
|
10975 | * object, else `false`.
|
10976 | *
|
10977 | * @static
|
10978 | * @memberOf _
|
10979 | * @category Collection
|
10980 | * @param {Array|Object|string} collection The collection to iterate over.
|
10981 | * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
|
10982 | * The iteratees to sort by, specified as individual values or arrays of values.
|
10983 | * @returns {Array} Returns the new sorted array.
|
10984 | * @example
|
10985 | *
|
10986 | * var users = [
|
10987 | * { 'user': 'fred', 'age': 48 },
|
10988 | * { 'user': 'barney', 'age': 36 },
|
10989 | * { 'user': 'fred', 'age': 42 },
|
10990 | * { 'user': 'barney', 'age': 34 }
|
10991 | * ];
|
10992 | *
|
10993 | * _.map(_.sortByAll(users, ['user', 'age']), _.values);
|
10994 | * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
|
10995 | *
|
10996 | * _.map(_.sortByAll(users, 'user', function(chr) {
|
10997 | * return Math.floor(chr.age / 10);
|
10998 | * }), _.values);
|
10999 | * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
|
11000 | */
|
11001 | var sortByAll = restParam(function(collection, iteratees) {
|
11002 | if (collection == null) {
|
11003 | return [];
|
11004 | }
|
11005 | var guard = iteratees[2];
|
11006 | if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
|
11007 | iteratees.length = 1;
|
11008 | }
|
11009 | return baseSortByOrder(collection, baseFlatten(iteratees), []);
|
11010 | });
|
11011 |
|
11012 | /**
|
11013 | * This method is like `_.sortByAll` except that it allows specifying the
|
11014 | * sort orders of the iteratees to sort by. If `orders` is unspecified, all
|
11015 | * values are sorted in ascending order. Otherwise, a value is sorted in
|
11016 | * ascending order if its corresponding order is "asc", and descending if "desc".
|
11017 | *
|
11018 | * If a property name is provided for an iteratee the created `_.property`
|
11019 | * style callback returns the property value of the given element.
|
11020 | *
|
11021 | * If an object is provided for an iteratee the created `_.matches` style
|
11022 | * callback returns `true` for elements that have the properties of the given
|
11023 | * object, else `false`.
|
11024 | *
|
11025 | * @static
|
11026 | * @memberOf _
|
11027 | * @category Collection
|
11028 | * @param {Array|Object|string} collection The collection to iterate over.
|
11029 | * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
|
11030 | * @param {boolean[]} [orders] The sort orders of `iteratees`.
|
11031 | * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
|
11032 | * @returns {Array} Returns the new sorted array.
|
11033 | * @example
|
11034 | *
|
11035 | * var users = [
|
11036 | * { 'user': 'fred', 'age': 48 },
|
11037 | * { 'user': 'barney', 'age': 34 },
|
11038 | * { 'user': 'fred', 'age': 42 },
|
11039 | * { 'user': 'barney', 'age': 36 }
|
11040 | * ];
|
11041 | *
|
11042 | * // sort by `user` in ascending order and by `age` in descending order
|
11043 | * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
|
11044 | * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
|
11045 | */
|
11046 | function sortByOrder(collection, iteratees, orders, guard) {
|
11047 | if (collection == null) {
|
11048 | return [];
|
11049 | }
|
11050 | if (guard && isIterateeCall(iteratees, orders, guard)) {
|
11051 | orders = undefined;
|
11052 | }
|
11053 | if (!isArray(iteratees)) {
|
11054 | iteratees = iteratees == null ? [] : [iteratees];
|
11055 | }
|
11056 | if (!isArray(orders)) {
|
11057 | orders = orders == null ? [] : [orders];
|
11058 | }
|
11059 | return baseSortByOrder(collection, iteratees, orders);
|
11060 | }
|
11061 |
|
11062 | /**
|
11063 | * Performs a deep comparison between each element in `collection` and the
|
11064 | * source object, returning an array of all elements that have equivalent
|
11065 | * property values.
|
11066 | *
|
11067 | * **Note:** This method supports comparing arrays, booleans, `Date` objects,
|
11068 | * numbers, `Object` objects, regexes, and strings. Objects are compared by
|
11069 | * their own, not inherited, enumerable properties. For comparing a single
|
11070 | * own or inherited property value see `_.matchesProperty`.
|
11071 | *
|
11072 | * @static
|
11073 | * @memberOf _
|
11074 | * @category Collection
|
11075 | * @param {Array|Object|string} collection The collection to search.
|
11076 | * @param {Object} source The object of property values to match.
|
11077 | * @returns {Array} Returns the new filtered array.
|
11078 | * @example
|
11079 | *
|
11080 | * var users = [
|
11081 | * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
|
11082 | * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
|
11083 | * ];
|
11084 | *
|
11085 | * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
|
11086 | * // => ['barney']
|
11087 | *
|
11088 | * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
|
11089 | * // => ['fred']
|
11090 | */
|
11091 | function where(collection, source) {
|
11092 | return filter(collection, baseMatches(source));
|
11093 | }
|
11094 |
|
11095 | /*------------------------------------------------------------------------*/
|
11096 |
|
11097 | /**
|
11098 | * Gets the number of milliseconds that have elapsed since the Unix epoch
|
11099 | * (1 January 1970 00:00:00 UTC).
|
11100 | *
|
11101 | * @static
|
11102 | * @memberOf _
|
11103 | * @category Date
|
11104 | * @example
|
11105 | *
|
11106 | * _.defer(function(stamp) {
|
11107 | * console.log(_.now() - stamp);
|
11108 | * }, _.now());
|
11109 | * // => logs the number of milliseconds it took for the deferred function to be invoked
|
11110 | */
|
11111 | var now = nativeNow || function() {
|
11112 | return new Date().getTime();
|
11113 | };
|
11114 |
|
11115 | /*------------------------------------------------------------------------*/
|
11116 |
|
11117 | /**
|
11118 | * The opposite of `_.before`; this method creates a function that invokes
|
11119 | * `func` once it is called `n` or more times.
|
11120 | *
|
11121 | * @static
|
11122 | * @memberOf _
|
11123 | * @category Function
|
11124 | * @param {number} n The number of calls before `func` is invoked.
|
11125 | * @param {Function} func The function to restrict.
|
11126 | * @returns {Function} Returns the new restricted function.
|
11127 | * @example
|
11128 | *
|
11129 | * var saves = ['profile', 'settings'];
|
11130 | *
|
11131 | * var done = _.after(saves.length, function() {
|
11132 | * console.log('done saving!');
|
11133 | * });
|
11134 | *
|
11135 | * _.forEach(saves, function(type) {
|
11136 | * asyncSave({ 'type': type, 'complete': done });
|
11137 | * });
|
11138 | * // => logs 'done saving!' after the two async saves have completed
|
11139 | */
|
11140 | function after(n, func) {
|
11141 | if (typeof func != 'function') {
|
11142 | if (typeof n == 'function') {
|
11143 | var temp = n;
|
11144 | n = func;
|
11145 | func = temp;
|
11146 | } else {
|
11147 | throw new TypeError(FUNC_ERROR_TEXT);
|
11148 | }
|
11149 | }
|
11150 | n = nativeIsFinite(n = +n) ? n : 0;
|
11151 | return function() {
|
11152 | if (--n < 1) {
|
11153 | return func.apply(this, arguments);
|
11154 | }
|
11155 | };
|
11156 | }
|
11157 |
|
11158 | /**
|
11159 | * Creates a function that accepts up to `n` arguments ignoring any
|
11160 | * additional arguments.
|
11161 | *
|
11162 | * @static
|
11163 | * @memberOf _
|
11164 | * @category Function
|
11165 | * @param {Function} func The function to cap arguments for.
|
11166 | * @param {number} [n=func.length] The arity cap.
|
11167 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
11168 | * @returns {Function} Returns the new function.
|
11169 | * @example
|
11170 | *
|
11171 | * _.map(['6', '8', '10'], _.ary(parseInt, 1));
|
11172 | * // => [6, 8, 10]
|
11173 | */
|
11174 | function ary(func, n, guard) {
|
11175 | if (guard && isIterateeCall(func, n, guard)) {
|
11176 | n = undefined;
|
11177 | }
|
11178 | n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
|
11179 | return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
|
11180 | }
|
11181 |
|
11182 | /**
|
11183 | * Creates a function that invokes `func`, with the `this` binding and arguments
|
11184 | * of the created function, while it is called less than `n` times. Subsequent
|
11185 | * calls to the created function return the result of the last `func` invocation.
|
11186 | *
|
11187 | * @static
|
11188 | * @memberOf _
|
11189 | * @category Function
|
11190 | * @param {number} n The number of calls at which `func` is no longer invoked.
|
11191 | * @param {Function} func The function to restrict.
|
11192 | * @returns {Function} Returns the new restricted function.
|
11193 | * @example
|
11194 | *
|
11195 | * jQuery('#add').on('click', _.before(5, addContactToList));
|
11196 | * // => allows adding up to 4 contacts to the list
|
11197 | */
|
11198 | function before(n, func) {
|
11199 | var result;
|
11200 | if (typeof func != 'function') {
|
11201 | if (typeof n == 'function') {
|
11202 | var temp = n;
|
11203 | n = func;
|
11204 | func = temp;
|
11205 | } else {
|
11206 | throw new TypeError(FUNC_ERROR_TEXT);
|
11207 | }
|
11208 | }
|
11209 | return function() {
|
11210 | if (--n > 0) {
|
11211 | result = func.apply(this, arguments);
|
11212 | }
|
11213 | if (n <= 1) {
|
11214 | func = undefined;
|
11215 | }
|
11216 | return result;
|
11217 | };
|
11218 | }
|
11219 |
|
11220 | /**
|
11221 | * Creates a function that invokes `func` with the `this` binding of `thisArg`
|
11222 | * and prepends any additional `_.bind` arguments to those provided to the
|
11223 | * bound function.
|
11224 | *
|
11225 | * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
|
11226 | * may be used as a placeholder for partially applied arguments.
|
11227 | *
|
11228 | * **Note:** Unlike native `Function#bind` this method does not set the "length"
|
11229 | * property of bound functions.
|
11230 | *
|
11231 | * @static
|
11232 | * @memberOf _
|
11233 | * @category Function
|
11234 | * @param {Function} func The function to bind.
|
11235 | * @param {*} thisArg The `this` binding of `func`.
|
11236 | * @param {...*} [partials] The arguments to be partially applied.
|
11237 | * @returns {Function} Returns the new bound function.
|
11238 | * @example
|
11239 | *
|
11240 | * var greet = function(greeting, punctuation) {
|
11241 | * return greeting + ' ' + this.user + punctuation;
|
11242 | * };
|
11243 | *
|
11244 | * var object = { 'user': 'fred' };
|
11245 | *
|
11246 | * var bound = _.bind(greet, object, 'hi');
|
11247 | * bound('!');
|
11248 | * // => 'hi fred!'
|
11249 | *
|
11250 | * // using placeholders
|
11251 | * var bound = _.bind(greet, object, _, '!');
|
11252 | * bound('hi');
|
11253 | * // => 'hi fred!'
|
11254 | */
|
11255 | var bind = restParam(function(func, thisArg, partials) {
|
11256 | var bitmask = BIND_FLAG;
|
11257 | if (partials.length) {
|
11258 | var holders = replaceHolders(partials, bind.placeholder);
|
11259 | bitmask |= PARTIAL_FLAG;
|
11260 | }
|
11261 | return createWrapper(func, bitmask, thisArg, partials, holders);
|
11262 | });
|
11263 |
|
11264 | /**
|
11265 | * Binds methods of an object to the object itself, overwriting the existing
|
11266 | * method. Method names may be specified as individual arguments or as arrays
|
11267 | * of method names. If no method names are provided all enumerable function
|
11268 | * properties, own and inherited, of `object` are bound.
|
11269 | *
|
11270 | * **Note:** This method does not set the "length" property of bound functions.
|
11271 | *
|
11272 | * @static
|
11273 | * @memberOf _
|
11274 | * @category Function
|
11275 | * @param {Object} object The object to bind and assign the bound methods to.
|
11276 | * @param {...(string|string[])} [methodNames] The object method names to bind,
|
11277 | * specified as individual method names or arrays of method names.
|
11278 | * @returns {Object} Returns `object`.
|
11279 | * @example
|
11280 | *
|
11281 | * var view = {
|
11282 | * 'label': 'docs',
|
11283 | * 'onClick': function() {
|
11284 | * console.log('clicked ' + this.label);
|
11285 | * }
|
11286 | * };
|
11287 | *
|
11288 | * _.bindAll(view);
|
11289 | * jQuery('#docs').on('click', view.onClick);
|
11290 | * // => logs 'clicked docs' when the element is clicked
|
11291 | */
|
11292 | var bindAll = restParam(function(object, methodNames) {
|
11293 | methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
|
11294 |
|
11295 | var index = -1,
|
11296 | length = methodNames.length;
|
11297 |
|
11298 | while (++index < length) {
|
11299 | var key = methodNames[index];
|
11300 | object[key] = createWrapper(object[key], BIND_FLAG, object);
|
11301 | }
|
11302 | return object;
|
11303 | });
|
11304 |
|
11305 | /**
|
11306 | * Creates a function that invokes the method at `object[key]` and prepends
|
11307 | * any additional `_.bindKey` arguments to those provided to the bound function.
|
11308 | *
|
11309 | * This method differs from `_.bind` by allowing bound functions to reference
|
11310 | * methods that may be redefined or don't yet exist.
|
11311 | * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
|
11312 | * for more details.
|
11313 | *
|
11314 | * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
|
11315 | * builds, may be used as a placeholder for partially applied arguments.
|
11316 | *
|
11317 | * @static
|
11318 | * @memberOf _
|
11319 | * @category Function
|
11320 | * @param {Object} object The object the method belongs to.
|
11321 | * @param {string} key The key of the method.
|
11322 | * @param {...*} [partials] The arguments to be partially applied.
|
11323 | * @returns {Function} Returns the new bound function.
|
11324 | * @example
|
11325 | *
|
11326 | * var object = {
|
11327 | * 'user': 'fred',
|
11328 | * 'greet': function(greeting, punctuation) {
|
11329 | * return greeting + ' ' + this.user + punctuation;
|
11330 | * }
|
11331 | * };
|
11332 | *
|
11333 | * var bound = _.bindKey(object, 'greet', 'hi');
|
11334 | * bound('!');
|
11335 | * // => 'hi fred!'
|
11336 | *
|
11337 | * object.greet = function(greeting, punctuation) {
|
11338 | * return greeting + 'ya ' + this.user + punctuation;
|
11339 | * };
|
11340 | *
|
11341 | * bound('!');
|
11342 | * // => 'hiya fred!'
|
11343 | *
|
11344 | * // using placeholders
|
11345 | * var bound = _.bindKey(object, 'greet', _, '!');
|
11346 | * bound('hi');
|
11347 | * // => 'hiya fred!'
|
11348 | */
|
11349 | var bindKey = restParam(function(object, key, partials) {
|
11350 | var bitmask = BIND_FLAG | BIND_KEY_FLAG;
|
11351 | if (partials.length) {
|
11352 | var holders = replaceHolders(partials, bindKey.placeholder);
|
11353 | bitmask |= PARTIAL_FLAG;
|
11354 | }
|
11355 | return createWrapper(key, bitmask, object, partials, holders);
|
11356 | });
|
11357 |
|
11358 | /**
|
11359 | * Creates a function that accepts one or more arguments of `func` that when
|
11360 | * called either invokes `func` returning its result, if all `func` arguments
|
11361 | * have been provided, or returns a function that accepts one or more of the
|
11362 | * remaining `func` arguments, and so on. The arity of `func` may be specified
|
11363 | * if `func.length` is not sufficient.
|
11364 | *
|
11365 | * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
|
11366 | * may be used as a placeholder for provided arguments.
|
11367 | *
|
11368 | * **Note:** This method does not set the "length" property of curried functions.
|
11369 | *
|
11370 | * @static
|
11371 | * @memberOf _
|
11372 | * @category Function
|
11373 | * @param {Function} func The function to curry.
|
11374 | * @param {number} [arity=func.length] The arity of `func`.
|
11375 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
11376 | * @returns {Function} Returns the new curried function.
|
11377 | * @example
|
11378 | *
|
11379 | * var abc = function(a, b, c) {
|
11380 | * return [a, b, c];
|
11381 | * };
|
11382 | *
|
11383 | * var curried = _.curry(abc);
|
11384 | *
|
11385 | * curried(1)(2)(3);
|
11386 | * // => [1, 2, 3]
|
11387 | *
|
11388 | * curried(1, 2)(3);
|
11389 | * // => [1, 2, 3]
|
11390 | *
|
11391 | * curried(1, 2, 3);
|
11392 | * // => [1, 2, 3]
|
11393 | *
|
11394 | * // using placeholders
|
11395 | * curried(1)(_, 3)(2);
|
11396 | * // => [1, 2, 3]
|
11397 | */
|
11398 | var curry = createCurry(CURRY_FLAG);
|
11399 |
|
11400 | /**
|
11401 | * This method is like `_.curry` except that arguments are applied to `func`
|
11402 | * in the manner of `_.partialRight` instead of `_.partial`.
|
11403 | *
|
11404 | * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
|
11405 | * builds, may be used as a placeholder for provided arguments.
|
11406 | *
|
11407 | * **Note:** This method does not set the "length" property of curried functions.
|
11408 | *
|
11409 | * @static
|
11410 | * @memberOf _
|
11411 | * @category Function
|
11412 | * @param {Function} func The function to curry.
|
11413 | * @param {number} [arity=func.length] The arity of `func`.
|
11414 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
11415 | * @returns {Function} Returns the new curried function.
|
11416 | * @example
|
11417 | *
|
11418 | * var abc = function(a, b, c) {
|
11419 | * return [a, b, c];
|
11420 | * };
|
11421 | *
|
11422 | * var curried = _.curryRight(abc);
|
11423 | *
|
11424 | * curried(3)(2)(1);
|
11425 | * // => [1, 2, 3]
|
11426 | *
|
11427 | * curried(2, 3)(1);
|
11428 | * // => [1, 2, 3]
|
11429 | *
|
11430 | * curried(1, 2, 3);
|
11431 | * // => [1, 2, 3]
|
11432 | *
|
11433 | * // using placeholders
|
11434 | * curried(3)(1, _)(2);
|
11435 | * // => [1, 2, 3]
|
11436 | */
|
11437 | var curryRight = createCurry(CURRY_RIGHT_FLAG);
|
11438 |
|
11439 | /**
|
11440 | * Creates a debounced function that delays invoking `func` until after `wait`
|
11441 | * milliseconds have elapsed since the last time the debounced function was
|
11442 | * invoked. The debounced function comes with a `cancel` method to cancel
|
11443 | * delayed invocations. Provide an options object to indicate that `func`
|
11444 | * should be invoked on the leading and/or trailing edge of the `wait` timeout.
|
11445 | * Subsequent calls to the debounced function return the result of the last
|
11446 | * `func` invocation.
|
11447 | *
|
11448 | * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
|
11449 | * on the trailing edge of the timeout only if the the debounced function is
|
11450 | * invoked more than once during the `wait` timeout.
|
11451 | *
|
11452 | * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
|
11453 | * for details over the differences between `_.debounce` and `_.throttle`.
|
11454 | *
|
11455 | * @static
|
11456 | * @memberOf _
|
11457 | * @category Function
|
11458 | * @param {Function} func The function to debounce.
|
11459 | * @param {number} [wait=0] The number of milliseconds to delay.
|
11460 | * @param {Object} [options] The options object.
|
11461 | * @param {boolean} [options.leading=false] Specify invoking on the leading
|
11462 | * edge of the timeout.
|
11463 | * @param {number} [options.maxWait] The maximum time `func` is allowed to be
|
11464 | * delayed before it is invoked.
|
11465 | * @param {boolean} [options.trailing=true] Specify invoking on the trailing
|
11466 | * edge of the timeout.
|
11467 | * @returns {Function} Returns the new debounced function.
|
11468 | * @example
|
11469 | *
|
11470 | * // avoid costly calculations while the window size is in flux
|
11471 | * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
|
11472 | *
|
11473 | * // invoke `sendMail` when the click event is fired, debouncing subsequent calls
|
11474 | * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
|
11475 | * 'leading': true,
|
11476 | * 'trailing': false
|
11477 | * }));
|
11478 | *
|
11479 | * // ensure `batchLog` is invoked once after 1 second of debounced calls
|
11480 | * var source = new EventSource('/stream');
|
11481 | * jQuery(source).on('message', _.debounce(batchLog, 250, {
|
11482 | * 'maxWait': 1000
|
11483 | * }));
|
11484 | *
|
11485 | * // cancel a debounced call
|
11486 | * var todoChanges = _.debounce(batchLog, 1000);
|
11487 | * Object.observe(models.todo, todoChanges);
|
11488 | *
|
11489 | * Object.observe(models, function(changes) {
|
11490 | * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
|
11491 | * todoChanges.cancel();
|
11492 | * }
|
11493 | * }, ['delete']);
|
11494 | *
|
11495 | * // ...at some point `models.todo` is changed
|
11496 | * models.todo.completed = true;
|
11497 | *
|
11498 | * // ...before 1 second has passed `models.todo` is deleted
|
11499 | * // which cancels the debounced `todoChanges` call
|
11500 | * delete models.todo;
|
11501 | */
|
11502 | function debounce(func, wait, options) {
|
11503 | var args,
|
11504 | maxTimeoutId,
|
11505 | result,
|
11506 | stamp,
|
11507 | thisArg,
|
11508 | timeoutId,
|
11509 | trailingCall,
|
11510 | lastCalled = 0,
|
11511 | maxWait = false,
|
11512 | trailing = true;
|
11513 |
|
11514 | if (typeof func != 'function') {
|
11515 | throw new TypeError(FUNC_ERROR_TEXT);
|
11516 | }
|
11517 | wait = wait < 0 ? 0 : (+wait || 0);
|
11518 | if (options === true) {
|
11519 | var leading = true;
|
11520 | trailing = false;
|
11521 | } else if (isObject(options)) {
|
11522 | leading = !!options.leading;
|
11523 | maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
|
11524 | trailing = 'trailing' in options ? !!options.trailing : trailing;
|
11525 | }
|
11526 |
|
11527 | function cancel() {
|
11528 | if (timeoutId) {
|
11529 | clearTimeout(timeoutId);
|
11530 | }
|
11531 | if (maxTimeoutId) {
|
11532 | clearTimeout(maxTimeoutId);
|
11533 | }
|
11534 | lastCalled = 0;
|
11535 | maxTimeoutId = timeoutId = trailingCall = undefined;
|
11536 | }
|
11537 |
|
11538 | function complete(isCalled, id) {
|
11539 | if (id) {
|
11540 | clearTimeout(id);
|
11541 | }
|
11542 | maxTimeoutId = timeoutId = trailingCall = undefined;
|
11543 | if (isCalled) {
|
11544 | lastCalled = now();
|
11545 | result = func.apply(thisArg, args);
|
11546 | if (!timeoutId && !maxTimeoutId) {
|
11547 | args = thisArg = undefined;
|
11548 | }
|
11549 | }
|
11550 | }
|
11551 |
|
11552 | function delayed() {
|
11553 | var remaining = wait - (now() - stamp);
|
11554 | if (remaining <= 0 || remaining > wait) {
|
11555 | complete(trailingCall, maxTimeoutId);
|
11556 | } else {
|
11557 | timeoutId = setTimeout(delayed, remaining);
|
11558 | }
|
11559 | }
|
11560 |
|
11561 | function maxDelayed() {
|
11562 | complete(trailing, timeoutId);
|
11563 | }
|
11564 |
|
11565 | function debounced() {
|
11566 | args = arguments;
|
11567 | stamp = now();
|
11568 | thisArg = this;
|
11569 | trailingCall = trailing && (timeoutId || !leading);
|
11570 |
|
11571 | if (maxWait === false) {
|
11572 | var leadingCall = leading && !timeoutId;
|
11573 | } else {
|
11574 | if (!maxTimeoutId && !leading) {
|
11575 | lastCalled = stamp;
|
11576 | }
|
11577 | var remaining = maxWait - (stamp - lastCalled),
|
11578 | isCalled = remaining <= 0 || remaining > maxWait;
|
11579 |
|
11580 | if (isCalled) {
|
11581 | if (maxTimeoutId) {
|
11582 | maxTimeoutId = clearTimeout(maxTimeoutId);
|
11583 | }
|
11584 | lastCalled = stamp;
|
11585 | result = func.apply(thisArg, args);
|
11586 | }
|
11587 | else if (!maxTimeoutId) {
|
11588 | maxTimeoutId = setTimeout(maxDelayed, remaining);
|
11589 | }
|
11590 | }
|
11591 | if (isCalled && timeoutId) {
|
11592 | timeoutId = clearTimeout(timeoutId);
|
11593 | }
|
11594 | else if (!timeoutId && wait !== maxWait) {
|
11595 | timeoutId = setTimeout(delayed, wait);
|
11596 | }
|
11597 | if (leadingCall) {
|
11598 | isCalled = true;
|
11599 | result = func.apply(thisArg, args);
|
11600 | }
|
11601 | if (isCalled && !timeoutId && !maxTimeoutId) {
|
11602 | args = thisArg = undefined;
|
11603 | }
|
11604 | return result;
|
11605 | }
|
11606 | debounced.cancel = cancel;
|
11607 | return debounced;
|
11608 | }
|
11609 |
|
11610 | /**
|
11611 | * Defers invoking the `func` until the current call stack has cleared. Any
|
11612 | * additional arguments are provided to `func` when it is invoked.
|
11613 | *
|
11614 | * @static
|
11615 | * @memberOf _
|
11616 | * @category Function
|
11617 | * @param {Function} func The function to defer.
|
11618 | * @param {...*} [args] The arguments to invoke the function with.
|
11619 | * @returns {number} Returns the timer id.
|
11620 | * @example
|
11621 | *
|
11622 | * _.defer(function(text) {
|
11623 | * console.log(text);
|
11624 | * }, 'deferred');
|
11625 | * // logs 'deferred' after one or more milliseconds
|
11626 | */
|
11627 | var defer = restParam(function(func, args) {
|
11628 | return baseDelay(func, 1, args);
|
11629 | });
|
11630 |
|
11631 | /**
|
11632 | * Invokes `func` after `wait` milliseconds. Any additional arguments are
|
11633 | * provided to `func` when it is invoked.
|
11634 | *
|
11635 | * @static
|
11636 | * @memberOf _
|
11637 | * @category Function
|
11638 | * @param {Function} func The function to delay.
|
11639 | * @param {number} wait The number of milliseconds to delay invocation.
|
11640 | * @param {...*} [args] The arguments to invoke the function with.
|
11641 | * @returns {number} Returns the timer id.
|
11642 | * @example
|
11643 | *
|
11644 | * _.delay(function(text) {
|
11645 | * console.log(text);
|
11646 | * }, 1000, 'later');
|
11647 | * // => logs 'later' after one second
|
11648 | */
|
11649 | var delay = restParam(function(func, wait, args) {
|
11650 | return baseDelay(func, wait, args);
|
11651 | });
|
11652 |
|
11653 | /**
|
11654 | * Creates a function that returns the result of invoking the provided
|
11655 | * functions with the `this` binding of the created function, where each
|
11656 | * successive invocation is supplied the return value of the previous.
|
11657 | *
|
11658 | * @static
|
11659 | * @memberOf _
|
11660 | * @category Function
|
11661 | * @param {...Function} [funcs] Functions to invoke.
|
11662 | * @returns {Function} Returns the new function.
|
11663 | * @example
|
11664 | *
|
11665 | * function square(n) {
|
11666 | * return n * n;
|
11667 | * }
|
11668 | *
|
11669 | * var addSquare = _.flow(_.add, square);
|
11670 | * addSquare(1, 2);
|
11671 | * // => 9
|
11672 | */
|
11673 | var flow = createFlow();
|
11674 |
|
11675 | /**
|
11676 | * This method is like `_.flow` except that it creates a function that
|
11677 | * invokes the provided functions from right to left.
|
11678 | *
|
11679 | * @static
|
11680 | * @memberOf _
|
11681 | * @alias backflow, compose
|
11682 | * @category Function
|
11683 | * @param {...Function} [funcs] Functions to invoke.
|
11684 | * @returns {Function} Returns the new function.
|
11685 | * @example
|
11686 | *
|
11687 | * function square(n) {
|
11688 | * return n * n;
|
11689 | * }
|
11690 | *
|
11691 | * var addSquare = _.flowRight(square, _.add);
|
11692 | * addSquare(1, 2);
|
11693 | * // => 9
|
11694 | */
|
11695 | var flowRight = createFlow(true);
|
11696 |
|
11697 | /**
|
11698 | * Creates a function that memoizes the result of `func`. If `resolver` is
|
11699 | * provided it determines the cache key for storing the result based on the
|
11700 | * arguments provided to the memoized function. By default, the first argument
|
11701 | * provided to the memoized function is coerced to a string and used as the
|
11702 | * cache key. The `func` is invoked with the `this` binding of the memoized
|
11703 | * function.
|
11704 | *
|
11705 | * **Note:** The cache is exposed as the `cache` property on the memoized
|
11706 | * function. Its creation may be customized by replacing the `_.memoize.Cache`
|
11707 | * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
|
11708 | * method interface of `get`, `has`, and `set`.
|
11709 | *
|
11710 | * @static
|
11711 | * @memberOf _
|
11712 | * @category Function
|
11713 | * @param {Function} func The function to have its output memoized.
|
11714 | * @param {Function} [resolver] The function to resolve the cache key.
|
11715 | * @returns {Function} Returns the new memoizing function.
|
11716 | * @example
|
11717 | *
|
11718 | * var upperCase = _.memoize(function(string) {
|
11719 | * return string.toUpperCase();
|
11720 | * });
|
11721 | *
|
11722 | * upperCase('fred');
|
11723 | * // => 'FRED'
|
11724 | *
|
11725 | * // modifying the result cache
|
11726 | * upperCase.cache.set('fred', 'BARNEY');
|
11727 | * upperCase('fred');
|
11728 | * // => 'BARNEY'
|
11729 | *
|
11730 | * // replacing `_.memoize.Cache`
|
11731 | * var object = { 'user': 'fred' };
|
11732 | * var other = { 'user': 'barney' };
|
11733 | * var identity = _.memoize(_.identity);
|
11734 | *
|
11735 | * identity(object);
|
11736 | * // => { 'user': 'fred' }
|
11737 | * identity(other);
|
11738 | * // => { 'user': 'fred' }
|
11739 | *
|
11740 | * _.memoize.Cache = WeakMap;
|
11741 | * var identity = _.memoize(_.identity);
|
11742 | *
|
11743 | * identity(object);
|
11744 | * // => { 'user': 'fred' }
|
11745 | * identity(other);
|
11746 | * // => { 'user': 'barney' }
|
11747 | */
|
11748 | function memoize(func, resolver) {
|
11749 | if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
|
11750 | throw new TypeError(FUNC_ERROR_TEXT);
|
11751 | }
|
11752 | var memoized = function() {
|
11753 | var args = arguments,
|
11754 | key = resolver ? resolver.apply(this, args) : args[0],
|
11755 | cache = memoized.cache;
|
11756 |
|
11757 | if (cache.has(key)) {
|
11758 | return cache.get(key);
|
11759 | }
|
11760 | var result = func.apply(this, args);
|
11761 | memoized.cache = cache.set(key, result);
|
11762 | return result;
|
11763 | };
|
11764 | memoized.cache = new memoize.Cache;
|
11765 | return memoized;
|
11766 | }
|
11767 |
|
11768 | /**
|
11769 | * Creates a function that runs each argument through a corresponding
|
11770 | * transform function.
|
11771 | *
|
11772 | * @static
|
11773 | * @memberOf _
|
11774 | * @category Function
|
11775 | * @param {Function} func The function to wrap.
|
11776 | * @param {...(Function|Function[])} [transforms] The functions to transform
|
11777 | * arguments, specified as individual functions or arrays of functions.
|
11778 | * @returns {Function} Returns the new function.
|
11779 | * @example
|
11780 | *
|
11781 | * function doubled(n) {
|
11782 | * return n * 2;
|
11783 | * }
|
11784 | *
|
11785 | * function square(n) {
|
11786 | * return n * n;
|
11787 | * }
|
11788 | *
|
11789 | * var modded = _.modArgs(function(x, y) {
|
11790 | * return [x, y];
|
11791 | * }, square, doubled);
|
11792 | *
|
11793 | * modded(1, 2);
|
11794 | * // => [1, 4]
|
11795 | *
|
11796 | * modded(5, 10);
|
11797 | * // => [25, 20]
|
11798 | */
|
11799 | var modArgs = restParam(function(func, transforms) {
|
11800 | transforms = baseFlatten(transforms);
|
11801 | if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
|
11802 | throw new TypeError(FUNC_ERROR_TEXT);
|
11803 | }
|
11804 | var length = transforms.length;
|
11805 | return restParam(function(args) {
|
11806 | var index = nativeMin(args.length, length);
|
11807 | while (index--) {
|
11808 | args[index] = transforms[index](args[index]);
|
11809 | }
|
11810 | return func.apply(this, args);
|
11811 | });
|
11812 | });
|
11813 |
|
11814 | /**
|
11815 | * Creates a function that negates the result of the predicate `func`. The
|
11816 | * `func` predicate is invoked with the `this` binding and arguments of the
|
11817 | * created function.
|
11818 | *
|
11819 | * @static
|
11820 | * @memberOf _
|
11821 | * @category Function
|
11822 | * @param {Function} predicate The predicate to negate.
|
11823 | * @returns {Function} Returns the new function.
|
11824 | * @example
|
11825 | *
|
11826 | * function isEven(n) {
|
11827 | * return n % 2 == 0;
|
11828 | * }
|
11829 | *
|
11830 | * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
|
11831 | * // => [1, 3, 5]
|
11832 | */
|
11833 | function negate(predicate) {
|
11834 | if (typeof predicate != 'function') {
|
11835 | throw new TypeError(FUNC_ERROR_TEXT);
|
11836 | }
|
11837 | return function() {
|
11838 | return !predicate.apply(this, arguments);
|
11839 | };
|
11840 | }
|
11841 |
|
11842 | /**
|
11843 | * Creates a function that is restricted to invoking `func` once. Repeat calls
|
11844 | * to the function return the value of the first call. The `func` is invoked
|
11845 | * with the `this` binding and arguments of the created function.
|
11846 | *
|
11847 | * @static
|
11848 | * @memberOf _
|
11849 | * @category Function
|
11850 | * @param {Function} func The function to restrict.
|
11851 | * @returns {Function} Returns the new restricted function.
|
11852 | * @example
|
11853 | *
|
11854 | * var initialize = _.once(createApplication);
|
11855 | * initialize();
|
11856 | * initialize();
|
11857 | * // `initialize` invokes `createApplication` once
|
11858 | */
|
11859 | function once(func) {
|
11860 | return before(2, func);
|
11861 | }
|
11862 |
|
11863 | /**
|
11864 | * Creates a function that invokes `func` with `partial` arguments prepended
|
11865 | * to those provided to the new function. This method is like `_.bind` except
|
11866 | * it does **not** alter the `this` binding.
|
11867 | *
|
11868 | * The `_.partial.placeholder` value, which defaults to `_` in monolithic
|
11869 | * builds, may be used as a placeholder for partially applied arguments.
|
11870 | *
|
11871 | * **Note:** This method does not set the "length" property of partially
|
11872 | * applied functions.
|
11873 | *
|
11874 | * @static
|
11875 | * @memberOf _
|
11876 | * @category Function
|
11877 | * @param {Function} func The function to partially apply arguments to.
|
11878 | * @param {...*} [partials] The arguments to be partially applied.
|
11879 | * @returns {Function} Returns the new partially applied function.
|
11880 | * @example
|
11881 | *
|
11882 | * var greet = function(greeting, name) {
|
11883 | * return greeting + ' ' + name;
|
11884 | * };
|
11885 | *
|
11886 | * var sayHelloTo = _.partial(greet, 'hello');
|
11887 | * sayHelloTo('fred');
|
11888 | * // => 'hello fred'
|
11889 | *
|
11890 | * // using placeholders
|
11891 | * var greetFred = _.partial(greet, _, 'fred');
|
11892 | * greetFred('hi');
|
11893 | * // => 'hi fred'
|
11894 | */
|
11895 | var partial = createPartial(PARTIAL_FLAG);
|
11896 |
|
11897 | /**
|
11898 | * This method is like `_.partial` except that partially applied arguments
|
11899 | * are appended to those provided to the new function.
|
11900 | *
|
11901 | * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
|
11902 | * builds, may be used as a placeholder for partially applied arguments.
|
11903 | *
|
11904 | * **Note:** This method does not set the "length" property of partially
|
11905 | * applied functions.
|
11906 | *
|
11907 | * @static
|
11908 | * @memberOf _
|
11909 | * @category Function
|
11910 | * @param {Function} func The function to partially apply arguments to.
|
11911 | * @param {...*} [partials] The arguments to be partially applied.
|
11912 | * @returns {Function} Returns the new partially applied function.
|
11913 | * @example
|
11914 | *
|
11915 | * var greet = function(greeting, name) {
|
11916 | * return greeting + ' ' + name;
|
11917 | * };
|
11918 | *
|
11919 | * var greetFred = _.partialRight(greet, 'fred');
|
11920 | * greetFred('hi');
|
11921 | * // => 'hi fred'
|
11922 | *
|
11923 | * // using placeholders
|
11924 | * var sayHelloTo = _.partialRight(greet, 'hello', _);
|
11925 | * sayHelloTo('fred');
|
11926 | * // => 'hello fred'
|
11927 | */
|
11928 | var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
|
11929 |
|
11930 | /**
|
11931 | * Creates a function that invokes `func` with arguments arranged according
|
11932 | * to the specified indexes where the argument value at the first index is
|
11933 | * provided as the first argument, the argument value at the second index is
|
11934 | * provided as the second argument, and so on.
|
11935 | *
|
11936 | * @static
|
11937 | * @memberOf _
|
11938 | * @category Function
|
11939 | * @param {Function} func The function to rearrange arguments for.
|
11940 | * @param {...(number|number[])} indexes The arranged argument indexes,
|
11941 | * specified as individual indexes or arrays of indexes.
|
11942 | * @returns {Function} Returns the new function.
|
11943 | * @example
|
11944 | *
|
11945 | * var rearged = _.rearg(function(a, b, c) {
|
11946 | * return [a, b, c];
|
11947 | * }, 2, 0, 1);
|
11948 | *
|
11949 | * rearged('b', 'c', 'a')
|
11950 | * // => ['a', 'b', 'c']
|
11951 | *
|
11952 | * var map = _.rearg(_.map, [1, 0]);
|
11953 | * map(function(n) {
|
11954 | * return n * 3;
|
11955 | * }, [1, 2, 3]);
|
11956 | * // => [3, 6, 9]
|
11957 | */
|
11958 | var rearg = restParam(function(func, indexes) {
|
11959 | return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes));
|
11960 | });
|
11961 |
|
11962 | /**
|
11963 | * Creates a function that invokes `func` with the `this` binding of the
|
11964 | * created function and arguments from `start` and beyond provided as an array.
|
11965 | *
|
11966 | * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
|
11967 | *
|
11968 | * @static
|
11969 | * @memberOf _
|
11970 | * @category Function
|
11971 | * @param {Function} func The function to apply a rest parameter to.
|
11972 | * @param {number} [start=func.length-1] The start position of the rest parameter.
|
11973 | * @returns {Function} Returns the new function.
|
11974 | * @example
|
11975 | *
|
11976 | * var say = _.restParam(function(what, names) {
|
11977 | * return what + ' ' + _.initial(names).join(', ') +
|
11978 | * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
|
11979 | * });
|
11980 | *
|
11981 | * say('hello', 'fred', 'barney', 'pebbles');
|
11982 | * // => 'hello fred, barney, & pebbles'
|
11983 | */
|
11984 | function restParam(func, start) {
|
11985 | if (typeof func != 'function') {
|
11986 | throw new TypeError(FUNC_ERROR_TEXT);
|
11987 | }
|
11988 | start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
|
11989 | return function() {
|
11990 | var args = arguments,
|
11991 | index = -1,
|
11992 | length = nativeMax(args.length - start, 0),
|
11993 | rest = Array(length);
|
11994 |
|
11995 | while (++index < length) {
|
11996 | rest[index] = args[start + index];
|
11997 | }
|
11998 | switch (start) {
|
11999 | case 0: return func.call(this, rest);
|
12000 | case 1: return func.call(this, args[0], rest);
|
12001 | case 2: return func.call(this, args[0], args[1], rest);
|
12002 | }
|
12003 | var otherArgs = Array(start + 1);
|
12004 | index = -1;
|
12005 | while (++index < start) {
|
12006 | otherArgs[index] = args[index];
|
12007 | }
|
12008 | otherArgs[start] = rest;
|
12009 | return func.apply(this, otherArgs);
|
12010 | };
|
12011 | }
|
12012 |
|
12013 | /**
|
12014 | * Creates a function that invokes `func` with the `this` binding of the created
|
12015 | * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
|
12016 | *
|
12017 | * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).
|
12018 | *
|
12019 | * @static
|
12020 | * @memberOf _
|
12021 | * @category Function
|
12022 | * @param {Function} func The function to spread arguments over.
|
12023 | * @returns {Function} Returns the new function.
|
12024 | * @example
|
12025 | *
|
12026 | * var say = _.spread(function(who, what) {
|
12027 | * return who + ' says ' + what;
|
12028 | * });
|
12029 | *
|
12030 | * say(['fred', 'hello']);
|
12031 | * // => 'fred says hello'
|
12032 | *
|
12033 | * // with a Promise
|
12034 | * var numbers = Promise.all([
|
12035 | * Promise.resolve(40),
|
12036 | * Promise.resolve(36)
|
12037 | * ]);
|
12038 | *
|
12039 | * numbers.then(_.spread(function(x, y) {
|
12040 | * return x + y;
|
12041 | * }));
|
12042 | * // => a Promise of 76
|
12043 | */
|
12044 | function spread(func) {
|
12045 | if (typeof func != 'function') {
|
12046 | throw new TypeError(FUNC_ERROR_TEXT);
|
12047 | }
|
12048 | return function(array) {
|
12049 | return func.apply(this, array);
|
12050 | };
|
12051 | }
|
12052 |
|
12053 | /**
|
12054 | * Creates a throttled function that only invokes `func` at most once per
|
12055 | * every `wait` milliseconds. The throttled function comes with a `cancel`
|
12056 | * method to cancel delayed invocations. Provide an options object to indicate
|
12057 | * that `func` should be invoked on the leading and/or trailing edge of the
|
12058 | * `wait` timeout. Subsequent calls to the throttled function return the
|
12059 | * result of the last `func` call.
|
12060 | *
|
12061 | * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
|
12062 | * on the trailing edge of the timeout only if the the throttled function is
|
12063 | * invoked more than once during the `wait` timeout.
|
12064 | *
|
12065 | * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
|
12066 | * for details over the differences between `_.throttle` and `_.debounce`.
|
12067 | *
|
12068 | * @static
|
12069 | * @memberOf _
|
12070 | * @category Function
|
12071 | * @param {Function} func The function to throttle.
|
12072 | * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
|
12073 | * @param {Object} [options] The options object.
|
12074 | * @param {boolean} [options.leading=true] Specify invoking on the leading
|
12075 | * edge of the timeout.
|
12076 | * @param {boolean} [options.trailing=true] Specify invoking on the trailing
|
12077 | * edge of the timeout.
|
12078 | * @returns {Function} Returns the new throttled function.
|
12079 | * @example
|
12080 | *
|
12081 | * // avoid excessively updating the position while scrolling
|
12082 | * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
|
12083 | *
|
12084 | * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
|
12085 | * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
|
12086 | * 'trailing': false
|
12087 | * }));
|
12088 | *
|
12089 | * // cancel a trailing throttled call
|
12090 | * jQuery(window).on('popstate', throttled.cancel);
|
12091 | */
|
12092 | function throttle(func, wait, options) {
|
12093 | var leading = true,
|
12094 | trailing = true;
|
12095 |
|
12096 | if (typeof func != 'function') {
|
12097 | throw new TypeError(FUNC_ERROR_TEXT);
|
12098 | }
|
12099 | if (options === false) {
|
12100 | leading = false;
|
12101 | } else if (isObject(options)) {
|
12102 | leading = 'leading' in options ? !!options.leading : leading;
|
12103 | trailing = 'trailing' in options ? !!options.trailing : trailing;
|
12104 | }
|
12105 | return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
|
12106 | }
|
12107 |
|
12108 | /**
|
12109 | * Creates a function that provides `value` to the wrapper function as its
|
12110 | * first argument. Any additional arguments provided to the function are
|
12111 | * appended to those provided to the wrapper function. The wrapper is invoked
|
12112 | * with the `this` binding of the created function.
|
12113 | *
|
12114 | * @static
|
12115 | * @memberOf _
|
12116 | * @category Function
|
12117 | * @param {*} value The value to wrap.
|
12118 | * @param {Function} wrapper The wrapper function.
|
12119 | * @returns {Function} Returns the new function.
|
12120 | * @example
|
12121 | *
|
12122 | * var p = _.wrap(_.escape, function(func, text) {
|
12123 | * return '<p>' + func(text) + '</p>';
|
12124 | * });
|
12125 | *
|
12126 | * p('fred, barney, & pebbles');
|
12127 | * // => '<p>fred, barney, & pebbles</p>'
|
12128 | */
|
12129 | function wrap(value, wrapper) {
|
12130 | wrapper = wrapper == null ? identity : wrapper;
|
12131 | return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []);
|
12132 | }
|
12133 |
|
12134 | /*------------------------------------------------------------------------*/
|
12135 |
|
12136 | /**
|
12137 | * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
|
12138 | * otherwise they are assigned by reference. If `customizer` is provided it is
|
12139 | * invoked to produce the cloned values. If `customizer` returns `undefined`
|
12140 | * cloning is handled by the method instead. The `customizer` is bound to
|
12141 | * `thisArg` and invoked with two argument; (value [, index|key, object]).
|
12142 | *
|
12143 | * **Note:** This method is loosely based on the
|
12144 | * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
|
12145 | * The enumerable properties of `arguments` objects and objects created by
|
12146 | * constructors other than `Object` are cloned to plain `Object` objects. An
|
12147 | * empty object is returned for uncloneable values such as functions, DOM nodes,
|
12148 | * Maps, Sets, and WeakMaps.
|
12149 | *
|
12150 | * @static
|
12151 | * @memberOf _
|
12152 | * @category Lang
|
12153 | * @param {*} value The value to clone.
|
12154 | * @param {boolean} [isDeep] Specify a deep clone.
|
12155 | * @param {Function} [customizer] The function to customize cloning values.
|
12156 | * @param {*} [thisArg] The `this` binding of `customizer`.
|
12157 | * @returns {*} Returns the cloned value.
|
12158 | * @example
|
12159 | *
|
12160 | * var users = [
|
12161 | * { 'user': 'barney' },
|
12162 | * { 'user': 'fred' }
|
12163 | * ];
|
12164 | *
|
12165 | * var shallow = _.clone(users);
|
12166 | * shallow[0] === users[0];
|
12167 | * // => true
|
12168 | *
|
12169 | * var deep = _.clone(users, true);
|
12170 | * deep[0] === users[0];
|
12171 | * // => false
|
12172 | *
|
12173 | * // using a customizer callback
|
12174 | * var el = _.clone(document.body, function(value) {
|
12175 | * if (_.isElement(value)) {
|
12176 | * return value.cloneNode(false);
|
12177 | * }
|
12178 | * });
|
12179 | *
|
12180 | * el === document.body
|
12181 | * // => false
|
12182 | * el.nodeName
|
12183 | * // => BODY
|
12184 | * el.childNodes.length;
|
12185 | * // => 0
|
12186 | */
|
12187 | function clone(value, isDeep, customizer, thisArg) {
|
12188 | if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
|
12189 | isDeep = false;
|
12190 | }
|
12191 | else if (typeof isDeep == 'function') {
|
12192 | thisArg = customizer;
|
12193 | customizer = isDeep;
|
12194 | isDeep = false;
|
12195 | }
|
12196 | return typeof customizer == 'function'
|
12197 | ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1))
|
12198 | : baseClone(value, isDeep);
|
12199 | }
|
12200 |
|
12201 | /**
|
12202 | * Creates a deep clone of `value`. If `customizer` is provided it is invoked
|
12203 | * to produce the cloned values. If `customizer` returns `undefined` cloning
|
12204 | * is handled by the method instead. The `customizer` is bound to `thisArg`
|
12205 | * and invoked with two argument; (value [, index|key, object]).
|
12206 | *
|
12207 | * **Note:** This method is loosely based on the
|
12208 | * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
|
12209 | * The enumerable properties of `arguments` objects and objects created by
|
12210 | * constructors other than `Object` are cloned to plain `Object` objects. An
|
12211 | * empty object is returned for uncloneable values such as functions, DOM nodes,
|
12212 | * Maps, Sets, and WeakMaps.
|
12213 | *
|
12214 | * @static
|
12215 | * @memberOf _
|
12216 | * @category Lang
|
12217 | * @param {*} value The value to deep clone.
|
12218 | * @param {Function} [customizer] The function to customize cloning values.
|
12219 | * @param {*} [thisArg] The `this` binding of `customizer`.
|
12220 | * @returns {*} Returns the deep cloned value.
|
12221 | * @example
|
12222 | *
|
12223 | * var users = [
|
12224 | * { 'user': 'barney' },
|
12225 | * { 'user': 'fred' }
|
12226 | * ];
|
12227 | *
|
12228 | * var deep = _.cloneDeep(users);
|
12229 | * deep[0] === users[0];
|
12230 | * // => false
|
12231 | *
|
12232 | * // using a customizer callback
|
12233 | * var el = _.cloneDeep(document.body, function(value) {
|
12234 | * if (_.isElement(value)) {
|
12235 | * return value.cloneNode(true);
|
12236 | * }
|
12237 | * });
|
12238 | *
|
12239 | * el === document.body
|
12240 | * // => false
|
12241 | * el.nodeName
|
12242 | * // => BODY
|
12243 | * el.childNodes.length;
|
12244 | * // => 20
|
12245 | */
|
12246 | function cloneDeep(value, customizer, thisArg) {
|
12247 | return typeof customizer == 'function'
|
12248 | ? baseClone(value, true, bindCallback(customizer, thisArg, 1))
|
12249 | : baseClone(value, true);
|
12250 | }
|
12251 |
|
12252 | /**
|
12253 | * Checks if `value` is greater than `other`.
|
12254 | *
|
12255 | * @static
|
12256 | * @memberOf _
|
12257 | * @category Lang
|
12258 | * @param {*} value The value to compare.
|
12259 | * @param {*} other The other value to compare.
|
12260 | * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`.
|
12261 | * @example
|
12262 | *
|
12263 | * _.gt(3, 1);
|
12264 | * // => true
|
12265 | *
|
12266 | * _.gt(3, 3);
|
12267 | * // => false
|
12268 | *
|
12269 | * _.gt(1, 3);
|
12270 | * // => false
|
12271 | */
|
12272 | function gt(value, other) {
|
12273 | return value > other;
|
12274 | }
|
12275 |
|
12276 | /**
|
12277 | * Checks if `value` is greater than or equal to `other`.
|
12278 | *
|
12279 | * @static
|
12280 | * @memberOf _
|
12281 | * @category Lang
|
12282 | * @param {*} value The value to compare.
|
12283 | * @param {*} other The other value to compare.
|
12284 | * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`.
|
12285 | * @example
|
12286 | *
|
12287 | * _.gte(3, 1);
|
12288 | * // => true
|
12289 | *
|
12290 | * _.gte(3, 3);
|
12291 | * // => true
|
12292 | *
|
12293 | * _.gte(1, 3);
|
12294 | * // => false
|
12295 | */
|
12296 | function gte(value, other) {
|
12297 | return value >= other;
|
12298 | }
|
12299 |
|
12300 | /**
|
12301 | * Checks if `value` is classified as an `arguments` object.
|
12302 | *
|
12303 | * @static
|
12304 | * @memberOf _
|
12305 | * @category Lang
|
12306 | * @param {*} value The value to check.
|
12307 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
12308 | * @example
|
12309 | *
|
12310 | * _.isArguments(function() { return arguments; }());
|
12311 | * // => true
|
12312 | *
|
12313 | * _.isArguments([1, 2, 3]);
|
12314 | * // => false
|
12315 | */
|
12316 | function isArguments(value) {
|
12317 | return isObjectLike(value) && isArrayLike(value) &&
|
12318 | hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
|
12319 | }
|
12320 |
|
12321 | /**
|
12322 | * Checks if `value` is classified as an `Array` object.
|
12323 | *
|
12324 | * @static
|
12325 | * @memberOf _
|
12326 | * @category Lang
|
12327 | * @param {*} value The value to check.
|
12328 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
12329 | * @example
|
12330 | *
|
12331 | * _.isArray([1, 2, 3]);
|
12332 | * // => true
|
12333 | *
|
12334 | * _.isArray(function() { return arguments; }());
|
12335 | * // => false
|
12336 | */
|
12337 | var isArray = nativeIsArray || function(value) {
|
12338 | return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
|
12339 | };
|
12340 |
|
12341 | /**
|
12342 | * Checks if `value` is classified as a boolean primitive or object.
|
12343 | *
|
12344 | * @static
|
12345 | * @memberOf _
|
12346 | * @category Lang
|
12347 | * @param {*} value The value to check.
|
12348 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
12349 | * @example
|
12350 | *
|
12351 | * _.isBoolean(false);
|
12352 | * // => true
|
12353 | *
|
12354 | * _.isBoolean(null);
|
12355 | * // => false
|
12356 | */
|
12357 | function isBoolean(value) {
|
12358 | return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag);
|
12359 | }
|
12360 |
|
12361 | /**
|
12362 | * Checks if `value` is classified as a `Date` object.
|
12363 | *
|
12364 | * @static
|
12365 | * @memberOf _
|
12366 | * @category Lang
|
12367 | * @param {*} value The value to check.
|
12368 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
12369 | * @example
|
12370 | *
|
12371 | * _.isDate(new Date);
|
12372 | * // => true
|
12373 | *
|
12374 | * _.isDate('Mon April 23 2012');
|
12375 | * // => false
|
12376 | */
|
12377 | function isDate(value) {
|
12378 | return isObjectLike(value) && objToString.call(value) == dateTag;
|
12379 | }
|
12380 |
|
12381 | /**
|
12382 | * Checks if `value` is a DOM element.
|
12383 | *
|
12384 | * @static
|
12385 | * @memberOf _
|
12386 | * @category Lang
|
12387 | * @param {*} value The value to check.
|
12388 | * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
|
12389 | * @example
|
12390 | *
|
12391 | * _.isElement(document.body);
|
12392 | * // => true
|
12393 | *
|
12394 | * _.isElement('<body>');
|
12395 | * // => false
|
12396 | */
|
12397 | function isElement(value) {
|
12398 | return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
|
12399 | }
|
12400 |
|
12401 | /**
|
12402 | * Checks if `value` is empty. A value is considered empty unless it is an
|
12403 | * `arguments` object, array, string, or jQuery-like collection with a length
|
12404 | * greater than `0` or an object with own enumerable properties.
|
12405 | *
|
12406 | * @static
|
12407 | * @memberOf _
|
12408 | * @category Lang
|
12409 | * @param {Array|Object|string} value The value to inspect.
|
12410 | * @returns {boolean} Returns `true` if `value` is empty, else `false`.
|
12411 | * @example
|
12412 | *
|
12413 | * _.isEmpty(null);
|
12414 | * // => true
|
12415 | *
|
12416 | * _.isEmpty(true);
|
12417 | * // => true
|
12418 | *
|
12419 | * _.isEmpty(1);
|
12420 | * // => true
|
12421 | *
|
12422 | * _.isEmpty([1, 2, 3]);
|
12423 | * // => false
|
12424 | *
|
12425 | * _.isEmpty({ 'a': 1 });
|
12426 | * // => false
|
12427 | */
|
12428 | function isEmpty(value) {
|
12429 | if (value == null) {
|
12430 | return true;
|
12431 | }
|
12432 | if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
|
12433 | (isObjectLike(value) && isFunction(value.splice)))) {
|
12434 | return !value.length;
|
12435 | }
|
12436 | return !keys(value).length;
|
12437 | }
|
12438 |
|
12439 | /**
|
12440 | * Performs a deep comparison between two values to determine if they are
|
12441 | * equivalent. If `customizer` is provided it is invoked to compare values.
|
12442 | * If `customizer` returns `undefined` comparisons are handled by the method
|
12443 | * instead. The `customizer` is bound to `thisArg` and invoked with three
|
12444 | * arguments: (value, other [, index|key]).
|
12445 | *
|
12446 | * **Note:** This method supports comparing arrays, booleans, `Date` objects,
|
12447 | * numbers, `Object` objects, regexes, and strings. Objects are compared by
|
12448 | * their own, not inherited, enumerable properties. Functions and DOM nodes
|
12449 | * are **not** supported. Provide a customizer function to extend support
|
12450 | * for comparing other values.
|
12451 | *
|
12452 | * @static
|
12453 | * @memberOf _
|
12454 | * @alias eq
|
12455 | * @category Lang
|
12456 | * @param {*} value The value to compare.
|
12457 | * @param {*} other The other value to compare.
|
12458 | * @param {Function} [customizer] The function to customize value comparisons.
|
12459 | * @param {*} [thisArg] The `this` binding of `customizer`.
|
12460 | * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
|
12461 | * @example
|
12462 | *
|
12463 | * var object = { 'user': 'fred' };
|
12464 | * var other = { 'user': 'fred' };
|
12465 | *
|
12466 | * object == other;
|
12467 | * // => false
|
12468 | *
|
12469 | * _.isEqual(object, other);
|
12470 | * // => true
|
12471 | *
|
12472 | * // using a customizer callback
|
12473 | * var array = ['hello', 'goodbye'];
|
12474 | * var other = ['hi', 'goodbye'];
|
12475 | *
|
12476 | * _.isEqual(array, other, function(value, other) {
|
12477 | * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
|
12478 | * return true;
|
12479 | * }
|
12480 | * });
|
12481 | * // => true
|
12482 | */
|
12483 | function isEqual(value, other, customizer, thisArg) {
|
12484 | customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
|
12485 | var result = customizer ? customizer(value, other) : undefined;
|
12486 | return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
|
12487 | }
|
12488 |
|
12489 | /**
|
12490 | * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
|
12491 | * `SyntaxError`, `TypeError`, or `URIError` object.
|
12492 | *
|
12493 | * @static
|
12494 | * @memberOf _
|
12495 | * @category Lang
|
12496 | * @param {*} value The value to check.
|
12497 | * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
|
12498 | * @example
|
12499 | *
|
12500 | * _.isError(new Error);
|
12501 | * // => true
|
12502 | *
|
12503 | * _.isError(Error);
|
12504 | * // => false
|
12505 | */
|
12506 | function isError(value) {
|
12507 | return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
|
12508 | }
|
12509 |
|
12510 | /**
|
12511 | * Checks if `value` is a finite primitive number.
|
12512 | *
|
12513 | * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite).
|
12514 | *
|
12515 | * @static
|
12516 | * @memberOf _
|
12517 | * @category Lang
|
12518 | * @param {*} value The value to check.
|
12519 | * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
|
12520 | * @example
|
12521 | *
|
12522 | * _.isFinite(10);
|
12523 | * // => true
|
12524 | *
|
12525 | * _.isFinite('10');
|
12526 | * // => false
|
12527 | *
|
12528 | * _.isFinite(true);
|
12529 | * // => false
|
12530 | *
|
12531 | * _.isFinite(Object(10));
|
12532 | * // => false
|
12533 | *
|
12534 | * _.isFinite(Infinity);
|
12535 | * // => false
|
12536 | */
|
12537 | function isFinite(value) {
|
12538 | return typeof value == 'number' && nativeIsFinite(value);
|
12539 | }
|
12540 |
|
12541 | /**
|
12542 | * Checks if `value` is classified as a `Function` object.
|
12543 | *
|
12544 | * @static
|
12545 | * @memberOf _
|
12546 | * @category Lang
|
12547 | * @param {*} value The value to check.
|
12548 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
12549 | * @example
|
12550 | *
|
12551 | * _.isFunction(_);
|
12552 | * // => true
|
12553 | *
|
12554 | * _.isFunction(/abc/);
|
12555 | * // => false
|
12556 | */
|
12557 | function isFunction(value) {
|
12558 | // The use of `Object#toString` avoids issues with the `typeof` operator
|
12559 | // in older versions of Chrome and Safari which return 'function' for regexes
|
12560 | // and Safari 8 equivalents which return 'object' for typed array constructors.
|
12561 | return isObject(value) && objToString.call(value) == funcTag;
|
12562 | }
|
12563 |
|
12564 | /**
|
12565 | * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
|
12566 | * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
|
12567 | *
|
12568 | * @static
|
12569 | * @memberOf _
|
12570 | * @category Lang
|
12571 | * @param {*} value The value to check.
|
12572 | * @returns {boolean} Returns `true` if `value` is an object, else `false`.
|
12573 | * @example
|
12574 | *
|
12575 | * _.isObject({});
|
12576 | * // => true
|
12577 | *
|
12578 | * _.isObject([1, 2, 3]);
|
12579 | * // => true
|
12580 | *
|
12581 | * _.isObject(1);
|
12582 | * // => false
|
12583 | */
|
12584 | function isObject(value) {
|
12585 | // Avoid a V8 JIT bug in Chrome 19-20.
|
12586 | // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
|
12587 | var type = typeof value;
|
12588 | return !!value && (type == 'object' || type == 'function');
|
12589 | }
|
12590 |
|
12591 | /**
|
12592 | * Performs a deep comparison between `object` and `source` to determine if
|
12593 | * `object` contains equivalent property values. If `customizer` is provided
|
12594 | * it is invoked to compare values. If `customizer` returns `undefined`
|
12595 | * comparisons are handled by the method instead. The `customizer` is bound
|
12596 | * to `thisArg` and invoked with three arguments: (value, other, index|key).
|
12597 | *
|
12598 | * **Note:** This method supports comparing properties of arrays, booleans,
|
12599 | * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
|
12600 | * and DOM nodes are **not** supported. Provide a customizer function to extend
|
12601 | * support for comparing other values.
|
12602 | *
|
12603 | * @static
|
12604 | * @memberOf _
|
12605 | * @category Lang
|
12606 | * @param {Object} object The object to inspect.
|
12607 | * @param {Object} source The object of property values to match.
|
12608 | * @param {Function} [customizer] The function to customize value comparisons.
|
12609 | * @param {*} [thisArg] The `this` binding of `customizer`.
|
12610 | * @returns {boolean} Returns `true` if `object` is a match, else `false`.
|
12611 | * @example
|
12612 | *
|
12613 | * var object = { 'user': 'fred', 'age': 40 };
|
12614 | *
|
12615 | * _.isMatch(object, { 'age': 40 });
|
12616 | * // => true
|
12617 | *
|
12618 | * _.isMatch(object, { 'age': 36 });
|
12619 | * // => false
|
12620 | *
|
12621 | * // using a customizer callback
|
12622 | * var object = { 'greeting': 'hello' };
|
12623 | * var source = { 'greeting': 'hi' };
|
12624 | *
|
12625 | * _.isMatch(object, source, function(value, other) {
|
12626 | * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
|
12627 | * });
|
12628 | * // => true
|
12629 | */
|
12630 | function isMatch(object, source, customizer, thisArg) {
|
12631 | customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
|
12632 | return baseIsMatch(object, getMatchData(source), customizer);
|
12633 | }
|
12634 |
|
12635 | /**
|
12636 | * Checks if `value` is `NaN`.
|
12637 | *
|
12638 | * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
|
12639 | * which returns `true` for `undefined` and other non-numeric values.
|
12640 | *
|
12641 | * @static
|
12642 | * @memberOf _
|
12643 | * @category Lang
|
12644 | * @param {*} value The value to check.
|
12645 | * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
|
12646 | * @example
|
12647 | *
|
12648 | * _.isNaN(NaN);
|
12649 | * // => true
|
12650 | *
|
12651 | * _.isNaN(new Number(NaN));
|
12652 | * // => true
|
12653 | *
|
12654 | * isNaN(undefined);
|
12655 | * // => true
|
12656 | *
|
12657 | * _.isNaN(undefined);
|
12658 | * // => false
|
12659 | */
|
12660 | function isNaN(value) {
|
12661 | // An `NaN` primitive is the only value that is not equal to itself.
|
12662 | // Perform the `toStringTag` check first to avoid errors with some host objects in IE.
|
12663 | return isNumber(value) && value != +value;
|
12664 | }
|
12665 |
|
12666 | /**
|
12667 | * Checks if `value` is a native function.
|
12668 | *
|
12669 | * @static
|
12670 | * @memberOf _
|
12671 | * @category Lang
|
12672 | * @param {*} value The value to check.
|
12673 | * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
|
12674 | * @example
|
12675 | *
|
12676 | * _.isNative(Array.prototype.push);
|
12677 | * // => true
|
12678 | *
|
12679 | * _.isNative(_);
|
12680 | * // => false
|
12681 | */
|
12682 | function isNative(value) {
|
12683 | if (value == null) {
|
12684 | return false;
|
12685 | }
|
12686 | if (isFunction(value)) {
|
12687 | return reIsNative.test(fnToString.call(value));
|
12688 | }
|
12689 | return isObjectLike(value) && reIsHostCtor.test(value);
|
12690 | }
|
12691 |
|
12692 | /**
|
12693 | * Checks if `value` is `null`.
|
12694 | *
|
12695 | * @static
|
12696 | * @memberOf _
|
12697 | * @category Lang
|
12698 | * @param {*} value The value to check.
|
12699 | * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
|
12700 | * @example
|
12701 | *
|
12702 | * _.isNull(null);
|
12703 | * // => true
|
12704 | *
|
12705 | * _.isNull(void 0);
|
12706 | * // => false
|
12707 | */
|
12708 | function isNull(value) {
|
12709 | return value === null;
|
12710 | }
|
12711 |
|
12712 | /**
|
12713 | * Checks if `value` is classified as a `Number` primitive or object.
|
12714 | *
|
12715 | * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
|
12716 | * as numbers, use the `_.isFinite` method.
|
12717 | *
|
12718 | * @static
|
12719 | * @memberOf _
|
12720 | * @category Lang
|
12721 | * @param {*} value The value to check.
|
12722 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
12723 | * @example
|
12724 | *
|
12725 | * _.isNumber(8.4);
|
12726 | * // => true
|
12727 | *
|
12728 | * _.isNumber(NaN);
|
12729 | * // => true
|
12730 | *
|
12731 | * _.isNumber('8.4');
|
12732 | * // => false
|
12733 | */
|
12734 | function isNumber(value) {
|
12735 | return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag);
|
12736 | }
|
12737 |
|
12738 | /**
|
12739 | * Checks if `value` is a plain object, that is, an object created by the
|
12740 | * `Object` constructor or one with a `[[Prototype]]` of `null`.
|
12741 | *
|
12742 | * **Note:** This method assumes objects created by the `Object` constructor
|
12743 | * have no inherited enumerable properties.
|
12744 | *
|
12745 | * @static
|
12746 | * @memberOf _
|
12747 | * @category Lang
|
12748 | * @param {*} value The value to check.
|
12749 | * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
|
12750 | * @example
|
12751 | *
|
12752 | * function Foo() {
|
12753 | * this.a = 1;
|
12754 | * }
|
12755 | *
|
12756 | * _.isPlainObject(new Foo);
|
12757 | * // => false
|
12758 | *
|
12759 | * _.isPlainObject([1, 2, 3]);
|
12760 | * // => false
|
12761 | *
|
12762 | * _.isPlainObject({ 'x': 0, 'y': 0 });
|
12763 | * // => true
|
12764 | *
|
12765 | * _.isPlainObject(Object.create(null));
|
12766 | * // => true
|
12767 | */
|
12768 | function isPlainObject(value) {
|
12769 | var Ctor;
|
12770 |
|
12771 | // Exit early for non `Object` objects.
|
12772 | if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
|
12773 | (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
|
12774 | return false;
|
12775 | }
|
12776 | // IE < 9 iterates inherited properties before own properties. If the first
|
12777 | // iterated property is an object's own property then there are no inherited
|
12778 | // enumerable properties.
|
12779 | var result;
|
12780 | // In most environments an object's own properties are iterated before
|
12781 | // its inherited properties. If the last iterated property is an object's
|
12782 | // own property then there are no inherited enumerable properties.
|
12783 | baseForIn(value, function(subValue, key) {
|
12784 | result = key;
|
12785 | });
|
12786 | return result === undefined || hasOwnProperty.call(value, result);
|
12787 | }
|
12788 |
|
12789 | /**
|
12790 | * Checks if `value` is classified as a `RegExp` object.
|
12791 | *
|
12792 | * @static
|
12793 | * @memberOf _
|
12794 | * @category Lang
|
12795 | * @param {*} value The value to check.
|
12796 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
12797 | * @example
|
12798 | *
|
12799 | * _.isRegExp(/abc/);
|
12800 | * // => true
|
12801 | *
|
12802 | * _.isRegExp('/abc/');
|
12803 | * // => false
|
12804 | */
|
12805 | function isRegExp(value) {
|
12806 | return isObject(value) && objToString.call(value) == regexpTag;
|
12807 | }
|
12808 |
|
12809 | /**
|
12810 | * Checks if `value` is classified as a `String` primitive or object.
|
12811 | *
|
12812 | * @static
|
12813 | * @memberOf _
|
12814 | * @category Lang
|
12815 | * @param {*} value The value to check.
|
12816 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
12817 | * @example
|
12818 | *
|
12819 | * _.isString('abc');
|
12820 | * // => true
|
12821 | *
|
12822 | * _.isString(1);
|
12823 | * // => false
|
12824 | */
|
12825 | function isString(value) {
|
12826 | return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
|
12827 | }
|
12828 |
|
12829 | /**
|
12830 | * Checks if `value` is classified as a typed array.
|
12831 | *
|
12832 | * @static
|
12833 | * @memberOf _
|
12834 | * @category Lang
|
12835 | * @param {*} value The value to check.
|
12836 | * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
|
12837 | * @example
|
12838 | *
|
12839 | * _.isTypedArray(new Uint8Array);
|
12840 | * // => true
|
12841 | *
|
12842 | * _.isTypedArray([]);
|
12843 | * // => false
|
12844 | */
|
12845 | function isTypedArray(value) {
|
12846 | return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
|
12847 | }
|
12848 |
|
12849 | /**
|
12850 | * Checks if `value` is `undefined`.
|
12851 | *
|
12852 | * @static
|
12853 | * @memberOf _
|
12854 | * @category Lang
|
12855 | * @param {*} value The value to check.
|
12856 | * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
|
12857 | * @example
|
12858 | *
|
12859 | * _.isUndefined(void 0);
|
12860 | * // => true
|
12861 | *
|
12862 | * _.isUndefined(null);
|
12863 | * // => false
|
12864 | */
|
12865 | function isUndefined(value) {
|
12866 | return value === undefined;
|
12867 | }
|
12868 |
|
12869 | /**
|
12870 | * Checks if `value` is less than `other`.
|
12871 | *
|
12872 | * @static
|
12873 | * @memberOf _
|
12874 | * @category Lang
|
12875 | * @param {*} value The value to compare.
|
12876 | * @param {*} other The other value to compare.
|
12877 | * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`.
|
12878 | * @example
|
12879 | *
|
12880 | * _.lt(1, 3);
|
12881 | * // => true
|
12882 | *
|
12883 | * _.lt(3, 3);
|
12884 | * // => false
|
12885 | *
|
12886 | * _.lt(3, 1);
|
12887 | * // => false
|
12888 | */
|
12889 | function lt(value, other) {
|
12890 | return value < other;
|
12891 | }
|
12892 |
|
12893 | /**
|
12894 | * Checks if `value` is less than or equal to `other`.
|
12895 | *
|
12896 | * @static
|
12897 | * @memberOf _
|
12898 | * @category Lang
|
12899 | * @param {*} value The value to compare.
|
12900 | * @param {*} other The other value to compare.
|
12901 | * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`.
|
12902 | * @example
|
12903 | *
|
12904 | * _.lte(1, 3);
|
12905 | * // => true
|
12906 | *
|
12907 | * _.lte(3, 3);
|
12908 | * // => true
|
12909 | *
|
12910 | * _.lte(3, 1);
|
12911 | * // => false
|
12912 | */
|
12913 | function lte(value, other) {
|
12914 | return value <= other;
|
12915 | }
|
12916 |
|
12917 | /**
|
12918 | * Converts `value` to an array.
|
12919 | *
|
12920 | * @static
|
12921 | * @memberOf _
|
12922 | * @category Lang
|
12923 | * @param {*} value The value to convert.
|
12924 | * @returns {Array} Returns the converted array.
|
12925 | * @example
|
12926 | *
|
12927 | * (function() {
|
12928 | * return _.toArray(arguments).slice(1);
|
12929 | * }(1, 2, 3));
|
12930 | * // => [2, 3]
|
12931 | */
|
12932 | function toArray(value) {
|
12933 | var length = value ? getLength(value) : 0;
|
12934 | if (!isLength(length)) {
|
12935 | return values(value);
|
12936 | }
|
12937 | if (!length) {
|
12938 | return [];
|
12939 | }
|
12940 | return arrayCopy(value);
|
12941 | }
|
12942 |
|
12943 | /**
|
12944 | * Converts `value` to a plain object flattening inherited enumerable
|
12945 | * properties of `value` to own properties of the plain object.
|
12946 | *
|
12947 | * @static
|
12948 | * @memberOf _
|
12949 | * @category Lang
|
12950 | * @param {*} value The value to convert.
|
12951 | * @returns {Object} Returns the converted plain object.
|
12952 | * @example
|
12953 | *
|
12954 | * function Foo() {
|
12955 | * this.b = 2;
|
12956 | * }
|
12957 | *
|
12958 | * Foo.prototype.c = 3;
|
12959 | *
|
12960 | * _.assign({ 'a': 1 }, new Foo);
|
12961 | * // => { 'a': 1, 'b': 2 }
|
12962 | *
|
12963 | * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
|
12964 | * // => { 'a': 1, 'b': 2, 'c': 3 }
|
12965 | */
|
12966 | function toPlainObject(value) {
|
12967 | return baseCopy(value, keysIn(value));
|
12968 | }
|
12969 |
|
12970 | /*------------------------------------------------------------------------*/
|
12971 |
|
12972 | /**
|
12973 | * Recursively merges own enumerable properties of the source object(s), that
|
12974 | * don't resolve to `undefined` into the destination object. Subsequent sources
|
12975 | * overwrite property assignments of previous sources. If `customizer` is
|
12976 | * provided it is invoked to produce the merged values of the destination and
|
12977 | * source properties. If `customizer` returns `undefined` merging is handled
|
12978 | * by the method instead. The `customizer` is bound to `thisArg` and invoked
|
12979 | * with five arguments: (objectValue, sourceValue, key, object, source).
|
12980 | *
|
12981 | * @static
|
12982 | * @memberOf _
|
12983 | * @category Object
|
12984 | * @param {Object} object The destination object.
|
12985 | * @param {...Object} [sources] The source objects.
|
12986 | * @param {Function} [customizer] The function to customize assigned values.
|
12987 | * @param {*} [thisArg] The `this` binding of `customizer`.
|
12988 | * @returns {Object} Returns `object`.
|
12989 | * @example
|
12990 | *
|
12991 | * var users = {
|
12992 | * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
|
12993 | * };
|
12994 | *
|
12995 | * var ages = {
|
12996 | * 'data': [{ 'age': 36 }, { 'age': 40 }]
|
12997 | * };
|
12998 | *
|
12999 | * _.merge(users, ages);
|
13000 | * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
|
13001 | *
|
13002 | * // using a customizer callback
|
13003 | * var object = {
|
13004 | * 'fruits': ['apple'],
|
13005 | * 'vegetables': ['beet']
|
13006 | * };
|
13007 | *
|
13008 | * var other = {
|
13009 | * 'fruits': ['banana'],
|
13010 | * 'vegetables': ['carrot']
|
13011 | * };
|
13012 | *
|
13013 | * _.merge(object, other, function(a, b) {
|
13014 | * if (_.isArray(a)) {
|
13015 | * return a.concat(b);
|
13016 | * }
|
13017 | * });
|
13018 | * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
|
13019 | */
|
13020 | var merge = createAssigner(baseMerge);
|
13021 |
|
13022 | /**
|
13023 | * Assigns own enumerable properties of source object(s) to the destination
|
13024 | * object. Subsequent sources overwrite property assignments of previous sources.
|
13025 | * If `customizer` is provided it is invoked to produce the assigned values.
|
13026 | * The `customizer` is bound to `thisArg` and invoked with five arguments:
|
13027 | * (objectValue, sourceValue, key, object, source).
|
13028 | *
|
13029 | * **Note:** This method mutates `object` and is based on
|
13030 | * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
|
13031 | *
|
13032 | * @static
|
13033 | * @memberOf _
|
13034 | * @alias extend
|
13035 | * @category Object
|
13036 | * @param {Object} object The destination object.
|
13037 | * @param {...Object} [sources] The source objects.
|
13038 | * @param {Function} [customizer] The function to customize assigned values.
|
13039 | * @param {*} [thisArg] The `this` binding of `customizer`.
|
13040 | * @returns {Object} Returns `object`.
|
13041 | * @example
|
13042 | *
|
13043 | * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
|
13044 | * // => { 'user': 'fred', 'age': 40 }
|
13045 | *
|
13046 | * // using a customizer callback
|
13047 | * var defaults = _.partialRight(_.assign, function(value, other) {
|
13048 | * return _.isUndefined(value) ? other : value;
|
13049 | * });
|
13050 | *
|
13051 | * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
|
13052 | * // => { 'user': 'barney', 'age': 36 }
|
13053 | */
|
13054 | var assign = createAssigner(function(object, source, customizer) {
|
13055 | return customizer
|
13056 | ? assignWith(object, source, customizer)
|
13057 | : baseAssign(object, source);
|
13058 | });
|
13059 |
|
13060 | /**
|
13061 | * Creates an object that inherits from the given `prototype` object. If a
|
13062 | * `properties` object is provided its own enumerable properties are assigned
|
13063 | * to the created object.
|
13064 | *
|
13065 | * @static
|
13066 | * @memberOf _
|
13067 | * @category Object
|
13068 | * @param {Object} prototype The object to inherit from.
|
13069 | * @param {Object} [properties] The properties to assign to the object.
|
13070 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
13071 | * @returns {Object} Returns the new object.
|
13072 | * @example
|
13073 | *
|
13074 | * function Shape() {
|
13075 | * this.x = 0;
|
13076 | * this.y = 0;
|
13077 | * }
|
13078 | *
|
13079 | * function Circle() {
|
13080 | * Shape.call(this);
|
13081 | * }
|
13082 | *
|
13083 | * Circle.prototype = _.create(Shape.prototype, {
|
13084 | * 'constructor': Circle
|
13085 | * });
|
13086 | *
|
13087 | * var circle = new Circle;
|
13088 | * circle instanceof Circle;
|
13089 | * // => true
|
13090 | *
|
13091 | * circle instanceof Shape;
|
13092 | * // => true
|
13093 | */
|
13094 | function create(prototype, properties, guard) {
|
13095 | var result = baseCreate(prototype);
|
13096 | if (guard && isIterateeCall(prototype, properties, guard)) {
|
13097 | properties = undefined;
|
13098 | }
|
13099 | return properties ? baseAssign(result, properties) : result;
|
13100 | }
|
13101 |
|
13102 | /**
|
13103 | * Assigns own enumerable properties of source object(s) to the destination
|
13104 | * object for all destination properties that resolve to `undefined`. Once a
|
13105 | * property is set, additional values of the same property are ignored.
|
13106 | *
|
13107 | * **Note:** This method mutates `object`.
|
13108 | *
|
13109 | * @static
|
13110 | * @memberOf _
|
13111 | * @category Object
|
13112 | * @param {Object} object The destination object.
|
13113 | * @param {...Object} [sources] The source objects.
|
13114 | * @returns {Object} Returns `object`.
|
13115 | * @example
|
13116 | *
|
13117 | * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
|
13118 | * // => { 'user': 'barney', 'age': 36 }
|
13119 | */
|
13120 | var defaults = createDefaults(assign, assignDefaults);
|
13121 |
|
13122 | /**
|
13123 | * This method is like `_.defaults` except that it recursively assigns
|
13124 | * default properties.
|
13125 | *
|
13126 | * **Note:** This method mutates `object`.
|
13127 | *
|
13128 | * @static
|
13129 | * @memberOf _
|
13130 | * @category Object
|
13131 | * @param {Object} object The destination object.
|
13132 | * @param {...Object} [sources] The source objects.
|
13133 | * @returns {Object} Returns `object`.
|
13134 | * @example
|
13135 | *
|
13136 | * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
|
13137 | * // => { 'user': { 'name': 'barney', 'age': 36 } }
|
13138 | *
|
13139 | */
|
13140 | var defaultsDeep = createDefaults(merge, mergeDefaults);
|
13141 |
|
13142 | /**
|
13143 | * This method is like `_.find` except that it returns the key of the first
|
13144 | * element `predicate` returns truthy for instead of the element itself.
|
13145 | *
|
13146 | * If a property name is provided for `predicate` the created `_.property`
|
13147 | * style callback returns the property value of the given element.
|
13148 | *
|
13149 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
13150 | * style callback returns `true` for elements that have a matching property
|
13151 | * value, else `false`.
|
13152 | *
|
13153 | * If an object is provided for `predicate` the created `_.matches` style
|
13154 | * callback returns `true` for elements that have the properties of the given
|
13155 | * object, else `false`.
|
13156 | *
|
13157 | * @static
|
13158 | * @memberOf _
|
13159 | * @category Object
|
13160 | * @param {Object} object The object to search.
|
13161 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
13162 | * per iteration.
|
13163 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
13164 | * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
|
13165 | * @example
|
13166 | *
|
13167 | * var users = {
|
13168 | * 'barney': { 'age': 36, 'active': true },
|
13169 | * 'fred': { 'age': 40, 'active': false },
|
13170 | * 'pebbles': { 'age': 1, 'active': true }
|
13171 | * };
|
13172 | *
|
13173 | * _.findKey(users, function(chr) {
|
13174 | * return chr.age < 40;
|
13175 | * });
|
13176 | * // => 'barney' (iteration order is not guaranteed)
|
13177 | *
|
13178 | * // using the `_.matches` callback shorthand
|
13179 | * _.findKey(users, { 'age': 1, 'active': true });
|
13180 | * // => 'pebbles'
|
13181 | *
|
13182 | * // using the `_.matchesProperty` callback shorthand
|
13183 | * _.findKey(users, 'active', false);
|
13184 | * // => 'fred'
|
13185 | *
|
13186 | * // using the `_.property` callback shorthand
|
13187 | * _.findKey(users, 'active');
|
13188 | * // => 'barney'
|
13189 | */
|
13190 | var findKey = createFindKey(baseForOwn);
|
13191 |
|
13192 | /**
|
13193 | * This method is like `_.findKey` except that it iterates over elements of
|
13194 | * a collection in the opposite order.
|
13195 | *
|
13196 | * If a property name is provided for `predicate` the created `_.property`
|
13197 | * style callback returns the property value of the given element.
|
13198 | *
|
13199 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
13200 | * style callback returns `true` for elements that have a matching property
|
13201 | * value, else `false`.
|
13202 | *
|
13203 | * If an object is provided for `predicate` the created `_.matches` style
|
13204 | * callback returns `true` for elements that have the properties of the given
|
13205 | * object, else `false`.
|
13206 | *
|
13207 | * @static
|
13208 | * @memberOf _
|
13209 | * @category Object
|
13210 | * @param {Object} object The object to search.
|
13211 | * @param {Function|Object|string} [predicate=_.identity] The function invoked
|
13212 | * per iteration.
|
13213 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
13214 | * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
|
13215 | * @example
|
13216 | *
|
13217 | * var users = {
|
13218 | * 'barney': { 'age': 36, 'active': true },
|
13219 | * 'fred': { 'age': 40, 'active': false },
|
13220 | * 'pebbles': { 'age': 1, 'active': true }
|
13221 | * };
|
13222 | *
|
13223 | * _.findLastKey(users, function(chr) {
|
13224 | * return chr.age < 40;
|
13225 | * });
|
13226 | * // => returns `pebbles` assuming `_.findKey` returns `barney`
|
13227 | *
|
13228 | * // using the `_.matches` callback shorthand
|
13229 | * _.findLastKey(users, { 'age': 36, 'active': true });
|
13230 | * // => 'barney'
|
13231 | *
|
13232 | * // using the `_.matchesProperty` callback shorthand
|
13233 | * _.findLastKey(users, 'active', false);
|
13234 | * // => 'fred'
|
13235 | *
|
13236 | * // using the `_.property` callback shorthand
|
13237 | * _.findLastKey(users, 'active');
|
13238 | * // => 'pebbles'
|
13239 | */
|
13240 | var findLastKey = createFindKey(baseForOwnRight);
|
13241 |
|
13242 | /**
|
13243 | * Iterates over own and inherited enumerable properties of an object invoking
|
13244 | * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
|
13245 | * with three arguments: (value, key, object). Iteratee functions may exit
|
13246 | * iteration early by explicitly returning `false`.
|
13247 | *
|
13248 | * @static
|
13249 | * @memberOf _
|
13250 | * @category Object
|
13251 | * @param {Object} object The object to iterate over.
|
13252 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
13253 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
13254 | * @returns {Object} Returns `object`.
|
13255 | * @example
|
13256 | *
|
13257 | * function Foo() {
|
13258 | * this.a = 1;
|
13259 | * this.b = 2;
|
13260 | * }
|
13261 | *
|
13262 | * Foo.prototype.c = 3;
|
13263 | *
|
13264 | * _.forIn(new Foo, function(value, key) {
|
13265 | * console.log(key);
|
13266 | * });
|
13267 | * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
|
13268 | */
|
13269 | var forIn = createForIn(baseFor);
|
13270 |
|
13271 | /**
|
13272 | * This method is like `_.forIn` except that it iterates over properties of
|
13273 | * `object` in the opposite order.
|
13274 | *
|
13275 | * @static
|
13276 | * @memberOf _
|
13277 | * @category Object
|
13278 | * @param {Object} object The object to iterate over.
|
13279 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
13280 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
13281 | * @returns {Object} Returns `object`.
|
13282 | * @example
|
13283 | *
|
13284 | * function Foo() {
|
13285 | * this.a = 1;
|
13286 | * this.b = 2;
|
13287 | * }
|
13288 | *
|
13289 | * Foo.prototype.c = 3;
|
13290 | *
|
13291 | * _.forInRight(new Foo, function(value, key) {
|
13292 | * console.log(key);
|
13293 | * });
|
13294 | * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
|
13295 | */
|
13296 | var forInRight = createForIn(baseForRight);
|
13297 |
|
13298 | /**
|
13299 | * Iterates over own enumerable properties of an object invoking `iteratee`
|
13300 | * for each property. The `iteratee` is bound to `thisArg` and invoked with
|
13301 | * three arguments: (value, key, object). Iteratee functions may exit iteration
|
13302 | * early by explicitly returning `false`.
|
13303 | *
|
13304 | * @static
|
13305 | * @memberOf _
|
13306 | * @category Object
|
13307 | * @param {Object} object The object to iterate over.
|
13308 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
13309 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
13310 | * @returns {Object} Returns `object`.
|
13311 | * @example
|
13312 | *
|
13313 | * function Foo() {
|
13314 | * this.a = 1;
|
13315 | * this.b = 2;
|
13316 | * }
|
13317 | *
|
13318 | * Foo.prototype.c = 3;
|
13319 | *
|
13320 | * _.forOwn(new Foo, function(value, key) {
|
13321 | * console.log(key);
|
13322 | * });
|
13323 | * // => logs 'a' and 'b' (iteration order is not guaranteed)
|
13324 | */
|
13325 | var forOwn = createForOwn(baseForOwn);
|
13326 |
|
13327 | /**
|
13328 | * This method is like `_.forOwn` except that it iterates over properties of
|
13329 | * `object` in the opposite order.
|
13330 | *
|
13331 | * @static
|
13332 | * @memberOf _
|
13333 | * @category Object
|
13334 | * @param {Object} object The object to iterate over.
|
13335 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
13336 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
13337 | * @returns {Object} Returns `object`.
|
13338 | * @example
|
13339 | *
|
13340 | * function Foo() {
|
13341 | * this.a = 1;
|
13342 | * this.b = 2;
|
13343 | * }
|
13344 | *
|
13345 | * Foo.prototype.c = 3;
|
13346 | *
|
13347 | * _.forOwnRight(new Foo, function(value, key) {
|
13348 | * console.log(key);
|
13349 | * });
|
13350 | * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
|
13351 | */
|
13352 | var forOwnRight = createForOwn(baseForOwnRight);
|
13353 |
|
13354 | /**
|
13355 | * Creates an array of function property names from all enumerable properties,
|
13356 | * own and inherited, of `object`.
|
13357 | *
|
13358 | * @static
|
13359 | * @memberOf _
|
13360 | * @alias methods
|
13361 | * @category Object
|
13362 | * @param {Object} object The object to inspect.
|
13363 | * @returns {Array} Returns the new array of property names.
|
13364 | * @example
|
13365 | *
|
13366 | * _.functions(_);
|
13367 | * // => ['after', 'ary', 'assign', ...]
|
13368 | */
|
13369 | function functions(object) {
|
13370 | return baseFunctions(object, keysIn(object));
|
13371 | }
|
13372 |
|
13373 | /**
|
13374 | * Gets the property value at `path` of `object`. If the resolved value is
|
13375 | * `undefined` the `defaultValue` is used in its place.
|
13376 | *
|
13377 | * @static
|
13378 | * @memberOf _
|
13379 | * @category Object
|
13380 | * @param {Object} object The object to query.
|
13381 | * @param {Array|string} path The path of the property to get.
|
13382 | * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
|
13383 | * @returns {*} Returns the resolved value.
|
13384 | * @example
|
13385 | *
|
13386 | * var object = { 'a': [{ 'b': { 'c': 3 } }] };
|
13387 | *
|
13388 | * _.get(object, 'a[0].b.c');
|
13389 | * // => 3
|
13390 | *
|
13391 | * _.get(object, ['a', '0', 'b', 'c']);
|
13392 | * // => 3
|
13393 | *
|
13394 | * _.get(object, 'a.b.c', 'default');
|
13395 | * // => 'default'
|
13396 | */
|
13397 | function get(object, path, defaultValue) {
|
13398 | var result = object == null ? undefined : baseGet(object, toPath(path), path + '');
|
13399 | return result === undefined ? defaultValue : result;
|
13400 | }
|
13401 |
|
13402 | /**
|
13403 | * Checks if `path` is a direct property.
|
13404 | *
|
13405 | * @static
|
13406 | * @memberOf _
|
13407 | * @category Object
|
13408 | * @param {Object} object The object to query.
|
13409 | * @param {Array|string} path The path to check.
|
13410 | * @returns {boolean} Returns `true` if `path` is a direct property, else `false`.
|
13411 | * @example
|
13412 | *
|
13413 | * var object = { 'a': { 'b': { 'c': 3 } } };
|
13414 | *
|
13415 | * _.has(object, 'a');
|
13416 | * // => true
|
13417 | *
|
13418 | * _.has(object, 'a.b.c');
|
13419 | * // => true
|
13420 | *
|
13421 | * _.has(object, ['a', 'b', 'c']);
|
13422 | * // => true
|
13423 | */
|
13424 | function has(object, path) {
|
13425 | if (object == null) {
|
13426 | return false;
|
13427 | }
|
13428 | var result = hasOwnProperty.call(object, path);
|
13429 | if (!result && !isKey(path)) {
|
13430 | path = toPath(path);
|
13431 | object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
|
13432 | if (object == null) {
|
13433 | return false;
|
13434 | }
|
13435 | path = last(path);
|
13436 | result = hasOwnProperty.call(object, path);
|
13437 | }
|
13438 | return result || (isLength(object.length) && isIndex(path, object.length) &&
|
13439 | (isArray(object) || isArguments(object)));
|
13440 | }
|
13441 |
|
13442 | /**
|
13443 | * Creates an object composed of the inverted keys and values of `object`.
|
13444 | * If `object` contains duplicate values, subsequent values overwrite property
|
13445 | * assignments of previous values unless `multiValue` is `true`.
|
13446 | *
|
13447 | * @static
|
13448 | * @memberOf _
|
13449 | * @category Object
|
13450 | * @param {Object} object The object to invert.
|
13451 | * @param {boolean} [multiValue] Allow multiple values per key.
|
13452 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
13453 | * @returns {Object} Returns the new inverted object.
|
13454 | * @example
|
13455 | *
|
13456 | * var object = { 'a': 1, 'b': 2, 'c': 1 };
|
13457 | *
|
13458 | * _.invert(object);
|
13459 | * // => { '1': 'c', '2': 'b' }
|
13460 | *
|
13461 | * // with `multiValue`
|
13462 | * _.invert(object, true);
|
13463 | * // => { '1': ['a', 'c'], '2': ['b'] }
|
13464 | */
|
13465 | function invert(object, multiValue, guard) {
|
13466 | if (guard && isIterateeCall(object, multiValue, guard)) {
|
13467 | multiValue = undefined;
|
13468 | }
|
13469 | var index = -1,
|
13470 | props = keys(object),
|
13471 | length = props.length,
|
13472 | result = {};
|
13473 |
|
13474 | while (++index < length) {
|
13475 | var key = props[index],
|
13476 | value = object[key];
|
13477 |
|
13478 | if (multiValue) {
|
13479 | if (hasOwnProperty.call(result, value)) {
|
13480 | result[value].push(key);
|
13481 | } else {
|
13482 | result[value] = [key];
|
13483 | }
|
13484 | }
|
13485 | else {
|
13486 | result[value] = key;
|
13487 | }
|
13488 | }
|
13489 | return result;
|
13490 | }
|
13491 |
|
13492 | /**
|
13493 | * Creates an array of the own enumerable property names of `object`.
|
13494 | *
|
13495 | * **Note:** Non-object values are coerced to objects. See the
|
13496 | * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
|
13497 | * for more details.
|
13498 | *
|
13499 | * @static
|
13500 | * @memberOf _
|
13501 | * @category Object
|
13502 | * @param {Object} object The object to query.
|
13503 | * @returns {Array} Returns the array of property names.
|
13504 | * @example
|
13505 | *
|
13506 | * function Foo() {
|
13507 | * this.a = 1;
|
13508 | * this.b = 2;
|
13509 | * }
|
13510 | *
|
13511 | * Foo.prototype.c = 3;
|
13512 | *
|
13513 | * _.keys(new Foo);
|
13514 | * // => ['a', 'b'] (iteration order is not guaranteed)
|
13515 | *
|
13516 | * _.keys('hi');
|
13517 | * // => ['0', '1']
|
13518 | */
|
13519 | var keys = !nativeKeys ? shimKeys : function(object) {
|
13520 | var Ctor = object == null ? undefined : object.constructor;
|
13521 | if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
|
13522 | (typeof object != 'function' && isArrayLike(object))) {
|
13523 | return shimKeys(object);
|
13524 | }
|
13525 | return isObject(object) ? nativeKeys(object) : [];
|
13526 | };
|
13527 |
|
13528 | /**
|
13529 | * Creates an array of the own and inherited enumerable property names of `object`.
|
13530 | *
|
13531 | * **Note:** Non-object values are coerced to objects.
|
13532 | *
|
13533 | * @static
|
13534 | * @memberOf _
|
13535 | * @category Object
|
13536 | * @param {Object} object The object to query.
|
13537 | * @returns {Array} Returns the array of property names.
|
13538 | * @example
|
13539 | *
|
13540 | * function Foo() {
|
13541 | * this.a = 1;
|
13542 | * this.b = 2;
|
13543 | * }
|
13544 | *
|
13545 | * Foo.prototype.c = 3;
|
13546 | *
|
13547 | * _.keysIn(new Foo);
|
13548 | * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
|
13549 | */
|
13550 | function keysIn(object) {
|
13551 | if (object == null) {
|
13552 | return [];
|
13553 | }
|
13554 | if (!isObject(object)) {
|
13555 | object = Object(object);
|
13556 | }
|
13557 | var length = object.length;
|
13558 | length = (length && isLength(length) &&
|
13559 | (isArray(object) || isArguments(object)) && length) || 0;
|
13560 |
|
13561 | var Ctor = object.constructor,
|
13562 | index = -1,
|
13563 | isProto = typeof Ctor == 'function' && Ctor.prototype === object,
|
13564 | result = Array(length),
|
13565 | skipIndexes = length > 0;
|
13566 |
|
13567 | while (++index < length) {
|
13568 | result[index] = (index + '');
|
13569 | }
|
13570 | for (var key in object) {
|
13571 | if (!(skipIndexes && isIndex(key, length)) &&
|
13572 | !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
|
13573 | result.push(key);
|
13574 | }
|
13575 | }
|
13576 | return result;
|
13577 | }
|
13578 |
|
13579 | /**
|
13580 | * The opposite of `_.mapValues`; this method creates an object with the
|
13581 | * same values as `object` and keys generated by running each own enumerable
|
13582 | * property of `object` through `iteratee`.
|
13583 | *
|
13584 | * @static
|
13585 | * @memberOf _
|
13586 | * @category Object
|
13587 | * @param {Object} object The object to iterate over.
|
13588 | * @param {Function|Object|string} [iteratee=_.identity] The function invoked
|
13589 | * per iteration.
|
13590 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
13591 | * @returns {Object} Returns the new mapped object.
|
13592 | * @example
|
13593 | *
|
13594 | * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
|
13595 | * return key + value;
|
13596 | * });
|
13597 | * // => { 'a1': 1, 'b2': 2 }
|
13598 | */
|
13599 | var mapKeys = createObjectMapper(true);
|
13600 |
|
13601 | /**
|
13602 | * Creates an object with the same keys as `object` and values generated by
|
13603 | * running each own enumerable property of `object` through `iteratee`. The
|
13604 | * iteratee function is bound to `thisArg` and invoked with three arguments:
|
13605 | * (value, key, object).
|
13606 | *
|
13607 | * If a property name is provided for `iteratee` the created `_.property`
|
13608 | * style callback returns the property value of the given element.
|
13609 | *
|
13610 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
13611 | * style callback returns `true` for elements that have a matching property
|
13612 | * value, else `false`.
|
13613 | *
|
13614 | * If an object is provided for `iteratee` the created `_.matches` style
|
13615 | * callback returns `true` for elements that have the properties of the given
|
13616 | * object, else `false`.
|
13617 | *
|
13618 | * @static
|
13619 | * @memberOf _
|
13620 | * @category Object
|
13621 | * @param {Object} object The object to iterate over.
|
13622 | * @param {Function|Object|string} [iteratee=_.identity] The function invoked
|
13623 | * per iteration.
|
13624 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
13625 | * @returns {Object} Returns the new mapped object.
|
13626 | * @example
|
13627 | *
|
13628 | * _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
|
13629 | * return n * 3;
|
13630 | * });
|
13631 | * // => { 'a': 3, 'b': 6 }
|
13632 | *
|
13633 | * var users = {
|
13634 | * 'fred': { 'user': 'fred', 'age': 40 },
|
13635 | * 'pebbles': { 'user': 'pebbles', 'age': 1 }
|
13636 | * };
|
13637 | *
|
13638 | * // using the `_.property` callback shorthand
|
13639 | * _.mapValues(users, 'age');
|
13640 | * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
|
13641 | */
|
13642 | var mapValues = createObjectMapper();
|
13643 |
|
13644 | /**
|
13645 | * The opposite of `_.pick`; this method creates an object composed of the
|
13646 | * own and inherited enumerable properties of `object` that are not omitted.
|
13647 | *
|
13648 | * @static
|
13649 | * @memberOf _
|
13650 | * @category Object
|
13651 | * @param {Object} object The source object.
|
13652 | * @param {Function|...(string|string[])} [predicate] The function invoked per
|
13653 | * iteration or property names to omit, specified as individual property
|
13654 | * names or arrays of property names.
|
13655 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
13656 | * @returns {Object} Returns the new object.
|
13657 | * @example
|
13658 | *
|
13659 | * var object = { 'user': 'fred', 'age': 40 };
|
13660 | *
|
13661 | * _.omit(object, 'age');
|
13662 | * // => { 'user': 'fred' }
|
13663 | *
|
13664 | * _.omit(object, _.isNumber);
|
13665 | * // => { 'user': 'fred' }
|
13666 | */
|
13667 | var omit = restParam(function(object, props) {
|
13668 | if (object == null) {
|
13669 | return {};
|
13670 | }
|
13671 | if (typeof props[0] != 'function') {
|
13672 | var props = arrayMap(baseFlatten(props), String);
|
13673 | return pickByArray(object, baseDifference(keysIn(object), props));
|
13674 | }
|
13675 | var predicate = bindCallback(props[0], props[1], 3);
|
13676 | return pickByCallback(object, function(value, key, object) {
|
13677 | return !predicate(value, key, object);
|
13678 | });
|
13679 | });
|
13680 |
|
13681 | /**
|
13682 | * Creates a two dimensional array of the key-value pairs for `object`,
|
13683 | * e.g. `[[key1, value1], [key2, value2]]`.
|
13684 | *
|
13685 | * @static
|
13686 | * @memberOf _
|
13687 | * @category Object
|
13688 | * @param {Object} object The object to query.
|
13689 | * @returns {Array} Returns the new array of key-value pairs.
|
13690 | * @example
|
13691 | *
|
13692 | * _.pairs({ 'barney': 36, 'fred': 40 });
|
13693 | * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
|
13694 | */
|
13695 | function pairs(object) {
|
13696 | object = toObject(object);
|
13697 |
|
13698 | var index = -1,
|
13699 | props = keys(object),
|
13700 | length = props.length,
|
13701 | result = Array(length);
|
13702 |
|
13703 | while (++index < length) {
|
13704 | var key = props[index];
|
13705 | result[index] = [key, object[key]];
|
13706 | }
|
13707 | return result;
|
13708 | }
|
13709 |
|
13710 | /**
|
13711 | * Creates an object composed of the picked `object` properties. Property
|
13712 | * names may be specified as individual arguments or as arrays of property
|
13713 | * names. If `predicate` is provided it is invoked for each property of `object`
|
13714 | * picking the properties `predicate` returns truthy for. The predicate is
|
13715 | * bound to `thisArg` and invoked with three arguments: (value, key, object).
|
13716 | *
|
13717 | * @static
|
13718 | * @memberOf _
|
13719 | * @category Object
|
13720 | * @param {Object} object The source object.
|
13721 | * @param {Function|...(string|string[])} [predicate] The function invoked per
|
13722 | * iteration or property names to pick, specified as individual property
|
13723 | * names or arrays of property names.
|
13724 | * @param {*} [thisArg] The `this` binding of `predicate`.
|
13725 | * @returns {Object} Returns the new object.
|
13726 | * @example
|
13727 | *
|
13728 | * var object = { 'user': 'fred', 'age': 40 };
|
13729 | *
|
13730 | * _.pick(object, 'user');
|
13731 | * // => { 'user': 'fred' }
|
13732 | *
|
13733 | * _.pick(object, _.isString);
|
13734 | * // => { 'user': 'fred' }
|
13735 | */
|
13736 | var pick = restParam(function(object, props) {
|
13737 | if (object == null) {
|
13738 | return {};
|
13739 | }
|
13740 | return typeof props[0] == 'function'
|
13741 | ? pickByCallback(object, bindCallback(props[0], props[1], 3))
|
13742 | : pickByArray(object, baseFlatten(props));
|
13743 | });
|
13744 |
|
13745 | /**
|
13746 | * This method is like `_.get` except that if the resolved value is a function
|
13747 | * it is invoked with the `this` binding of its parent object and its result
|
13748 | * is returned.
|
13749 | *
|
13750 | * @static
|
13751 | * @memberOf _
|
13752 | * @category Object
|
13753 | * @param {Object} object The object to query.
|
13754 | * @param {Array|string} path The path of the property to resolve.
|
13755 | * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
|
13756 | * @returns {*} Returns the resolved value.
|
13757 | * @example
|
13758 | *
|
13759 | * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
|
13760 | *
|
13761 | * _.result(object, 'a[0].b.c1');
|
13762 | * // => 3
|
13763 | *
|
13764 | * _.result(object, 'a[0].b.c2');
|
13765 | * // => 4
|
13766 | *
|
13767 | * _.result(object, 'a.b.c', 'default');
|
13768 | * // => 'default'
|
13769 | *
|
13770 | * _.result(object, 'a.b.c', _.constant('default'));
|
13771 | * // => 'default'
|
13772 | */
|
13773 | function result(object, path, defaultValue) {
|
13774 | var result = object == null ? undefined : object[path];
|
13775 | if (result === undefined) {
|
13776 | if (object != null && !isKey(path, object)) {
|
13777 | path = toPath(path);
|
13778 | object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
|
13779 | result = object == null ? undefined : object[last(path)];
|
13780 | }
|
13781 | result = result === undefined ? defaultValue : result;
|
13782 | }
|
13783 | return isFunction(result) ? result.call(object) : result;
|
13784 | }
|
13785 |
|
13786 | /**
|
13787 | * Sets the property value of `path` on `object`. If a portion of `path`
|
13788 | * does not exist it is created.
|
13789 | *
|
13790 | * @static
|
13791 | * @memberOf _
|
13792 | * @category Object
|
13793 | * @param {Object} object The object to augment.
|
13794 | * @param {Array|string} path The path of the property to set.
|
13795 | * @param {*} value The value to set.
|
13796 | * @returns {Object} Returns `object`.
|
13797 | * @example
|
13798 | *
|
13799 | * var object = { 'a': [{ 'b': { 'c': 3 } }] };
|
13800 | *
|
13801 | * _.set(object, 'a[0].b.c', 4);
|
13802 | * console.log(object.a[0].b.c);
|
13803 | * // => 4
|
13804 | *
|
13805 | * _.set(object, 'x[0].y.z', 5);
|
13806 | * console.log(object.x[0].y.z);
|
13807 | * // => 5
|
13808 | */
|
13809 | function set(object, path, value) {
|
13810 | if (object == null) {
|
13811 | return object;
|
13812 | }
|
13813 | var pathKey = (path + '');
|
13814 | path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
|
13815 |
|
13816 | var index = -1,
|
13817 | length = path.length,
|
13818 | lastIndex = length - 1,
|
13819 | nested = object;
|
13820 |
|
13821 | while (nested != null && ++index < length) {
|
13822 | var key = path[index];
|
13823 | if (isObject(nested)) {
|
13824 | if (index == lastIndex) {
|
13825 | nested[key] = value;
|
13826 | } else if (nested[key] == null) {
|
13827 | nested[key] = isIndex(path[index + 1]) ? [] : {};
|
13828 | }
|
13829 | }
|
13830 | nested = nested[key];
|
13831 | }
|
13832 | return object;
|
13833 | }
|
13834 |
|
13835 | /**
|
13836 | * An alternative to `_.reduce`; this method transforms `object` to a new
|
13837 | * `accumulator` object which is the result of running each of its own enumerable
|
13838 | * properties through `iteratee`, with each invocation potentially mutating
|
13839 | * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
|
13840 | * with four arguments: (accumulator, value, key, object). Iteratee functions
|
13841 | * may exit iteration early by explicitly returning `false`.
|
13842 | *
|
13843 | * @static
|
13844 | * @memberOf _
|
13845 | * @category Object
|
13846 | * @param {Array|Object} object The object to iterate over.
|
13847 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
13848 | * @param {*} [accumulator] The custom accumulator value.
|
13849 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
13850 | * @returns {*} Returns the accumulated value.
|
13851 | * @example
|
13852 | *
|
13853 | * _.transform([2, 3, 4], function(result, n) {
|
13854 | * result.push(n *= n);
|
13855 | * return n % 2 == 0;
|
13856 | * });
|
13857 | * // => [4, 9]
|
13858 | *
|
13859 | * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
|
13860 | * result[key] = n * 3;
|
13861 | * });
|
13862 | * // => { 'a': 3, 'b': 6 }
|
13863 | */
|
13864 | function transform(object, iteratee, accumulator, thisArg) {
|
13865 | var isArr = isArray(object) || isTypedArray(object);
|
13866 | iteratee = getCallback(iteratee, thisArg, 4);
|
13867 |
|
13868 | if (accumulator == null) {
|
13869 | if (isArr || isObject(object)) {
|
13870 | var Ctor = object.constructor;
|
13871 | if (isArr) {
|
13872 | accumulator = isArray(object) ? new Ctor : [];
|
13873 | } else {
|
13874 | accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
|
13875 | }
|
13876 | } else {
|
13877 | accumulator = {};
|
13878 | }
|
13879 | }
|
13880 | (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
|
13881 | return iteratee(accumulator, value, index, object);
|
13882 | });
|
13883 | return accumulator;
|
13884 | }
|
13885 |
|
13886 | /**
|
13887 | * Creates an array of the own enumerable property values of `object`.
|
13888 | *
|
13889 | * **Note:** Non-object values are coerced to objects.
|
13890 | *
|
13891 | * @static
|
13892 | * @memberOf _
|
13893 | * @category Object
|
13894 | * @param {Object} object The object to query.
|
13895 | * @returns {Array} Returns the array of property values.
|
13896 | * @example
|
13897 | *
|
13898 | * function Foo() {
|
13899 | * this.a = 1;
|
13900 | * this.b = 2;
|
13901 | * }
|
13902 | *
|
13903 | * Foo.prototype.c = 3;
|
13904 | *
|
13905 | * _.values(new Foo);
|
13906 | * // => [1, 2] (iteration order is not guaranteed)
|
13907 | *
|
13908 | * _.values('hi');
|
13909 | * // => ['h', 'i']
|
13910 | */
|
13911 | function values(object) {
|
13912 | return baseValues(object, keys(object));
|
13913 | }
|
13914 |
|
13915 | /**
|
13916 | * Creates an array of the own and inherited enumerable property values
|
13917 | * of `object`.
|
13918 | *
|
13919 | * **Note:** Non-object values are coerced to objects.
|
13920 | *
|
13921 | * @static
|
13922 | * @memberOf _
|
13923 | * @category Object
|
13924 | * @param {Object} object The object to query.
|
13925 | * @returns {Array} Returns the array of property values.
|
13926 | * @example
|
13927 | *
|
13928 | * function Foo() {
|
13929 | * this.a = 1;
|
13930 | * this.b = 2;
|
13931 | * }
|
13932 | *
|
13933 | * Foo.prototype.c = 3;
|
13934 | *
|
13935 | * _.valuesIn(new Foo);
|
13936 | * // => [1, 2, 3] (iteration order is not guaranteed)
|
13937 | */
|
13938 | function valuesIn(object) {
|
13939 | return baseValues(object, keysIn(object));
|
13940 | }
|
13941 |
|
13942 | /*------------------------------------------------------------------------*/
|
13943 |
|
13944 | /**
|
13945 | * Checks if `n` is between `start` and up to but not including, `end`. If
|
13946 | * `end` is not specified it is set to `start` with `start` then set to `0`.
|
13947 | *
|
13948 | * @static
|
13949 | * @memberOf _
|
13950 | * @category Number
|
13951 | * @param {number} n The number to check.
|
13952 | * @param {number} [start=0] The start of the range.
|
13953 | * @param {number} end The end of the range.
|
13954 | * @returns {boolean} Returns `true` if `n` is in the range, else `false`.
|
13955 | * @example
|
13956 | *
|
13957 | * _.inRange(3, 2, 4);
|
13958 | * // => true
|
13959 | *
|
13960 | * _.inRange(4, 8);
|
13961 | * // => true
|
13962 | *
|
13963 | * _.inRange(4, 2);
|
13964 | * // => false
|
13965 | *
|
13966 | * _.inRange(2, 2);
|
13967 | * // => false
|
13968 | *
|
13969 | * _.inRange(1.2, 2);
|
13970 | * // => true
|
13971 | *
|
13972 | * _.inRange(5.2, 4);
|
13973 | * // => false
|
13974 | */
|
13975 | function inRange(value, start, end) {
|
13976 | start = +start || 0;
|
13977 | if (end === undefined) {
|
13978 | end = start;
|
13979 | start = 0;
|
13980 | } else {
|
13981 | end = +end || 0;
|
13982 | }
|
13983 | return value >= nativeMin(start, end) && value < nativeMax(start, end);
|
13984 | }
|
13985 |
|
13986 | /**
|
13987 | * Produces a random number between `min` and `max` (inclusive). If only one
|
13988 | * argument is provided a number between `0` and the given number is returned.
|
13989 | * If `floating` is `true`, or either `min` or `max` are floats, a floating-point
|
13990 | * number is returned instead of an integer.
|
13991 | *
|
13992 | * @static
|
13993 | * @memberOf _
|
13994 | * @category Number
|
13995 | * @param {number} [min=0] The minimum possible value.
|
13996 | * @param {number} [max=1] The maximum possible value.
|
13997 | * @param {boolean} [floating] Specify returning a floating-point number.
|
13998 | * @returns {number} Returns the random number.
|
13999 | * @example
|
14000 | *
|
14001 | * _.random(0, 5);
|
14002 | * // => an integer between 0 and 5
|
14003 | *
|
14004 | * _.random(5);
|
14005 | * // => also an integer between 0 and 5
|
14006 | *
|
14007 | * _.random(5, true);
|
14008 | * // => a floating-point number between 0 and 5
|
14009 | *
|
14010 | * _.random(1.2, 5.2);
|
14011 | * // => a floating-point number between 1.2 and 5.2
|
14012 | */
|
14013 | function random(min, max, floating) {
|
14014 | if (floating && isIterateeCall(min, max, floating)) {
|
14015 | max = floating = undefined;
|
14016 | }
|
14017 | var noMin = min == null,
|
14018 | noMax = max == null;
|
14019 |
|
14020 | if (floating == null) {
|
14021 | if (noMax && typeof min == 'boolean') {
|
14022 | floating = min;
|
14023 | min = 1;
|
14024 | }
|
14025 | else if (typeof max == 'boolean') {
|
14026 | floating = max;
|
14027 | noMax = true;
|
14028 | }
|
14029 | }
|
14030 | if (noMin && noMax) {
|
14031 | max = 1;
|
14032 | noMax = false;
|
14033 | }
|
14034 | min = +min || 0;
|
14035 | if (noMax) {
|
14036 | max = min;
|
14037 | min = 0;
|
14038 | } else {
|
14039 | max = +max || 0;
|
14040 | }
|
14041 | if (floating || min % 1 || max % 1) {
|
14042 | var rand = nativeRandom();
|
14043 | return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
|
14044 | }
|
14045 | return baseRandom(min, max);
|
14046 | }
|
14047 |
|
14048 | /*------------------------------------------------------------------------*/
|
14049 |
|
14050 | /**
|
14051 | * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
|
14052 | *
|
14053 | * @static
|
14054 | * @memberOf _
|
14055 | * @category String
|
14056 | * @param {string} [string=''] The string to convert.
|
14057 | * @returns {string} Returns the camel cased string.
|
14058 | * @example
|
14059 | *
|
14060 | * _.camelCase('Foo Bar');
|
14061 | * // => 'fooBar'
|
14062 | *
|
14063 | * _.camelCase('--foo-bar');
|
14064 | * // => 'fooBar'
|
14065 | *
|
14066 | * _.camelCase('__foo_bar__');
|
14067 | * // => 'fooBar'
|
14068 | */
|
14069 | var camelCase = createCompounder(function(result, word, index) {
|
14070 | word = word.toLowerCase();
|
14071 | return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);
|
14072 | });
|
14073 |
|
14074 | /**
|
14075 | * Capitalizes the first character of `string`.
|
14076 | *
|
14077 | * @static
|
14078 | * @memberOf _
|
14079 | * @category String
|
14080 | * @param {string} [string=''] The string to capitalize.
|
14081 | * @returns {string} Returns the capitalized string.
|
14082 | * @example
|
14083 | *
|
14084 | * _.capitalize('fred');
|
14085 | * // => 'Fred'
|
14086 | */
|
14087 | function capitalize(string) {
|
14088 | string = baseToString(string);
|
14089 | return string && (string.charAt(0).toUpperCase() + string.slice(1));
|
14090 | }
|
14091 |
|
14092 | /**
|
14093 | * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
|
14094 | * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
|
14095 | *
|
14096 | * @static
|
14097 | * @memberOf _
|
14098 | * @category String
|
14099 | * @param {string} [string=''] The string to deburr.
|
14100 | * @returns {string} Returns the deburred string.
|
14101 | * @example
|
14102 | *
|
14103 | * _.deburr('déjà vu');
|
14104 | * // => 'deja vu'
|
14105 | */
|
14106 | function deburr(string) {
|
14107 | string = baseToString(string);
|
14108 | return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
|
14109 | }
|
14110 |
|
14111 | /**
|
14112 | * Checks if `string` ends with the given target string.
|
14113 | *
|
14114 | * @static
|
14115 | * @memberOf _
|
14116 | * @category String
|
14117 | * @param {string} [string=''] The string to search.
|
14118 | * @param {string} [target] The string to search for.
|
14119 | * @param {number} [position=string.length] The position to search from.
|
14120 | * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
|
14121 | * @example
|
14122 | *
|
14123 | * _.endsWith('abc', 'c');
|
14124 | * // => true
|
14125 | *
|
14126 | * _.endsWith('abc', 'b');
|
14127 | * // => false
|
14128 | *
|
14129 | * _.endsWith('abc', 'b', 2);
|
14130 | * // => true
|
14131 | */
|
14132 | function endsWith(string, target, position) {
|
14133 | string = baseToString(string);
|
14134 | target = (target + '');
|
14135 |
|
14136 | var length = string.length;
|
14137 | position = position === undefined
|
14138 | ? length
|
14139 | : nativeMin(position < 0 ? 0 : (+position || 0), length);
|
14140 |
|
14141 | position -= target.length;
|
14142 | return position >= 0 && string.indexOf(target, position) == position;
|
14143 | }
|
14144 |
|
14145 | /**
|
14146 | * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
|
14147 | * their corresponding HTML entities.
|
14148 | *
|
14149 | * **Note:** No other characters are escaped. To escape additional characters
|
14150 | * use a third-party library like [_he_](https://mths.be/he).
|
14151 | *
|
14152 | * Though the ">" character is escaped for symmetry, characters like
|
14153 | * ">" and "/" don't need escaping in HTML and have no special meaning
|
14154 | * unless they're part of a tag or unquoted attribute value.
|
14155 | * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
|
14156 | * (under "semi-related fun fact") for more details.
|
14157 | *
|
14158 | * Backticks are escaped because in Internet Explorer < 9, they can break out
|
14159 | * of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
|
14160 | * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
|
14161 | * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
|
14162 | * for more details.
|
14163 | *
|
14164 | * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
|
14165 | * to reduce XSS vectors.
|
14166 | *
|
14167 | * @static
|
14168 | * @memberOf _
|
14169 | * @category String
|
14170 | * @param {string} [string=''] The string to escape.
|
14171 | * @returns {string} Returns the escaped string.
|
14172 | * @example
|
14173 | *
|
14174 | * _.escape('fred, barney, & pebbles');
|
14175 | * // => 'fred, barney, & pebbles'
|
14176 | */
|
14177 | function escape(string) {
|
14178 | // Reset `lastIndex` because in IE < 9 `String#replace` does not.
|
14179 | string = baseToString(string);
|
14180 | return (string && reHasUnescapedHtml.test(string))
|
14181 | ? string.replace(reUnescapedHtml, escapeHtmlChar)
|
14182 | : string;
|
14183 | }
|
14184 |
|
14185 | /**
|
14186 | * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
|
14187 | * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
|
14188 | *
|
14189 | * @static
|
14190 | * @memberOf _
|
14191 | * @category String
|
14192 | * @param {string} [string=''] The string to escape.
|
14193 | * @returns {string} Returns the escaped string.
|
14194 | * @example
|
14195 | *
|
14196 | * _.escapeRegExp('[lodash](https://lodash.com/)');
|
14197 | * // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
|
14198 | */
|
14199 | function escapeRegExp(string) {
|
14200 | string = baseToString(string);
|
14201 | return (string && reHasRegExpChars.test(string))
|
14202 | ? string.replace(reRegExpChars, escapeRegExpChar)
|
14203 | : (string || '(?:)');
|
14204 | }
|
14205 |
|
14206 | /**
|
14207 | * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
|
14208 | *
|
14209 | * @static
|
14210 | * @memberOf _
|
14211 | * @category String
|
14212 | * @param {string} [string=''] The string to convert.
|
14213 | * @returns {string} Returns the kebab cased string.
|
14214 | * @example
|
14215 | *
|
14216 | * _.kebabCase('Foo Bar');
|
14217 | * // => 'foo-bar'
|
14218 | *
|
14219 | * _.kebabCase('fooBar');
|
14220 | * // => 'foo-bar'
|
14221 | *
|
14222 | * _.kebabCase('__foo_bar__');
|
14223 | * // => 'foo-bar'
|
14224 | */
|
14225 | var kebabCase = createCompounder(function(result, word, index) {
|
14226 | return result + (index ? '-' : '') + word.toLowerCase();
|
14227 | });
|
14228 |
|
14229 | /**
|
14230 | * Pads `string` on the left and right sides if it's shorter than `length`.
|
14231 | * Padding characters are truncated if they can't be evenly divided by `length`.
|
14232 | *
|
14233 | * @static
|
14234 | * @memberOf _
|
14235 | * @category String
|
14236 | * @param {string} [string=''] The string to pad.
|
14237 | * @param {number} [length=0] The padding length.
|
14238 | * @param {string} [chars=' '] The string used as padding.
|
14239 | * @returns {string} Returns the padded string.
|
14240 | * @example
|
14241 | *
|
14242 | * _.pad('abc', 8);
|
14243 | * // => ' abc '
|
14244 | *
|
14245 | * _.pad('abc', 8, '_-');
|
14246 | * // => '_-abc_-_'
|
14247 | *
|
14248 | * _.pad('abc', 3);
|
14249 | * // => 'abc'
|
14250 | */
|
14251 | function pad(string, length, chars) {
|
14252 | string = baseToString(string);
|
14253 | length = +length;
|
14254 |
|
14255 | var strLength = string.length;
|
14256 | if (strLength >= length || !nativeIsFinite(length)) {
|
14257 | return string;
|
14258 | }
|
14259 | var mid = (length - strLength) / 2,
|
14260 | leftLength = nativeFloor(mid),
|
14261 | rightLength = nativeCeil(mid);
|
14262 |
|
14263 | chars = createPadding('', rightLength, chars);
|
14264 | return chars.slice(0, leftLength) + string + chars;
|
14265 | }
|
14266 |
|
14267 | /**
|
14268 | * Pads `string` on the left side if it's shorter than `length`. Padding
|
14269 | * characters are truncated if they exceed `length`.
|
14270 | *
|
14271 | * @static
|
14272 | * @memberOf _
|
14273 | * @category String
|
14274 | * @param {string} [string=''] The string to pad.
|
14275 | * @param {number} [length=0] The padding length.
|
14276 | * @param {string} [chars=' '] The string used as padding.
|
14277 | * @returns {string} Returns the padded string.
|
14278 | * @example
|
14279 | *
|
14280 | * _.padLeft('abc', 6);
|
14281 | * // => ' abc'
|
14282 | *
|
14283 | * _.padLeft('abc', 6, '_-');
|
14284 | * // => '_-_abc'
|
14285 | *
|
14286 | * _.padLeft('abc', 3);
|
14287 | * // => 'abc'
|
14288 | */
|
14289 | var padLeft = createPadDir();
|
14290 |
|
14291 | /**
|
14292 | * Pads `string` on the right side if it's shorter than `length`. Padding
|
14293 | * characters are truncated if they exceed `length`.
|
14294 | *
|
14295 | * @static
|
14296 | * @memberOf _
|
14297 | * @category String
|
14298 | * @param {string} [string=''] The string to pad.
|
14299 | * @param {number} [length=0] The padding length.
|
14300 | * @param {string} [chars=' '] The string used as padding.
|
14301 | * @returns {string} Returns the padded string.
|
14302 | * @example
|
14303 | *
|
14304 | * _.padRight('abc', 6);
|
14305 | * // => 'abc '
|
14306 | *
|
14307 | * _.padRight('abc', 6, '_-');
|
14308 | * // => 'abc_-_'
|
14309 | *
|
14310 | * _.padRight('abc', 3);
|
14311 | * // => 'abc'
|
14312 | */
|
14313 | var padRight = createPadDir(true);
|
14314 |
|
14315 | /**
|
14316 | * Converts `string` to an integer of the specified radix. If `radix` is
|
14317 | * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
|
14318 | * in which case a `radix` of `16` is used.
|
14319 | *
|
14320 | * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
|
14321 | * of `parseInt`.
|
14322 | *
|
14323 | * @static
|
14324 | * @memberOf _
|
14325 | * @category String
|
14326 | * @param {string} string The string to convert.
|
14327 | * @param {number} [radix] The radix to interpret `value` by.
|
14328 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
14329 | * @returns {number} Returns the converted integer.
|
14330 | * @example
|
14331 | *
|
14332 | * _.parseInt('08');
|
14333 | * // => 8
|
14334 | *
|
14335 | * _.map(['6', '08', '10'], _.parseInt);
|
14336 | * // => [6, 8, 10]
|
14337 | */
|
14338 | function parseInt(string, radix, guard) {
|
14339 | // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
|
14340 | // Chrome fails to trim leading <BOM> whitespace characters.
|
14341 | // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
|
14342 | if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
|
14343 | radix = 0;
|
14344 | } else if (radix) {
|
14345 | radix = +radix;
|
14346 | }
|
14347 | string = trim(string);
|
14348 | return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
|
14349 | }
|
14350 |
|
14351 | /**
|
14352 | * Repeats the given string `n` times.
|
14353 | *
|
14354 | * @static
|
14355 | * @memberOf _
|
14356 | * @category String
|
14357 | * @param {string} [string=''] The string to repeat.
|
14358 | * @param {number} [n=0] The number of times to repeat the string.
|
14359 | * @returns {string} Returns the repeated string.
|
14360 | * @example
|
14361 | *
|
14362 | * _.repeat('*', 3);
|
14363 | * // => '***'
|
14364 | *
|
14365 | * _.repeat('abc', 2);
|
14366 | * // => 'abcabc'
|
14367 | *
|
14368 | * _.repeat('abc', 0);
|
14369 | * // => ''
|
14370 | */
|
14371 | function repeat(string, n) {
|
14372 | var result = '';
|
14373 | string = baseToString(string);
|
14374 | n = +n;
|
14375 | if (n < 1 || !string || !nativeIsFinite(n)) {
|
14376 | return result;
|
14377 | }
|
14378 | // Leverage the exponentiation by squaring algorithm for a faster repeat.
|
14379 | // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
|
14380 | do {
|
14381 | if (n % 2) {
|
14382 | result += string;
|
14383 | }
|
14384 | n = nativeFloor(n / 2);
|
14385 | string += string;
|
14386 | } while (n);
|
14387 |
|
14388 | return result;
|
14389 | }
|
14390 |
|
14391 | /**
|
14392 | * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
|
14393 | *
|
14394 | * @static
|
14395 | * @memberOf _
|
14396 | * @category String
|
14397 | * @param {string} [string=''] The string to convert.
|
14398 | * @returns {string} Returns the snake cased string.
|
14399 | * @example
|
14400 | *
|
14401 | * _.snakeCase('Foo Bar');
|
14402 | * // => 'foo_bar'
|
14403 | *
|
14404 | * _.snakeCase('fooBar');
|
14405 | * // => 'foo_bar'
|
14406 | *
|
14407 | * _.snakeCase('--foo-bar');
|
14408 | * // => 'foo_bar'
|
14409 | */
|
14410 | var snakeCase = createCompounder(function(result, word, index) {
|
14411 | return result + (index ? '_' : '') + word.toLowerCase();
|
14412 | });
|
14413 |
|
14414 | /**
|
14415 | * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
|
14416 | *
|
14417 | * @static
|
14418 | * @memberOf _
|
14419 | * @category String
|
14420 | * @param {string} [string=''] The string to convert.
|
14421 | * @returns {string} Returns the start cased string.
|
14422 | * @example
|
14423 | *
|
14424 | * _.startCase('--foo-bar');
|
14425 | * // => 'Foo Bar'
|
14426 | *
|
14427 | * _.startCase('fooBar');
|
14428 | * // => 'Foo Bar'
|
14429 | *
|
14430 | * _.startCase('__foo_bar__');
|
14431 | * // => 'Foo Bar'
|
14432 | */
|
14433 | var startCase = createCompounder(function(result, word, index) {
|
14434 | return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
|
14435 | });
|
14436 |
|
14437 | /**
|
14438 | * Checks if `string` starts with the given target string.
|
14439 | *
|
14440 | * @static
|
14441 | * @memberOf _
|
14442 | * @category String
|
14443 | * @param {string} [string=''] The string to search.
|
14444 | * @param {string} [target] The string to search for.
|
14445 | * @param {number} [position=0] The position to search from.
|
14446 | * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
|
14447 | * @example
|
14448 | *
|
14449 | * _.startsWith('abc', 'a');
|
14450 | * // => true
|
14451 | *
|
14452 | * _.startsWith('abc', 'b');
|
14453 | * // => false
|
14454 | *
|
14455 | * _.startsWith('abc', 'b', 1);
|
14456 | * // => true
|
14457 | */
|
14458 | function startsWith(string, target, position) {
|
14459 | string = baseToString(string);
|
14460 | position = position == null
|
14461 | ? 0
|
14462 | : nativeMin(position < 0 ? 0 : (+position || 0), string.length);
|
14463 |
|
14464 | return string.lastIndexOf(target, position) == position;
|
14465 | }
|
14466 |
|
14467 | /**
|
14468 | * Creates a compiled template function that can interpolate data properties
|
14469 | * in "interpolate" delimiters, HTML-escape interpolated data properties in
|
14470 | * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
|
14471 | * properties may be accessed as free variables in the template. If a setting
|
14472 | * object is provided it takes precedence over `_.templateSettings` values.
|
14473 | *
|
14474 | * **Note:** In the development build `_.template` utilizes
|
14475 | * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
|
14476 | * for easier debugging.
|
14477 | *
|
14478 | * For more information on precompiling templates see
|
14479 | * [lodash's custom builds documentation](https://lodash.com/custom-builds).
|
14480 | *
|
14481 | * For more information on Chrome extension sandboxes see
|
14482 | * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
|
14483 | *
|
14484 | * @static
|
14485 | * @memberOf _
|
14486 | * @category String
|
14487 | * @param {string} [string=''] The template string.
|
14488 | * @param {Object} [options] The options object.
|
14489 | * @param {RegExp} [options.escape] The HTML "escape" delimiter.
|
14490 | * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
|
14491 | * @param {Object} [options.imports] An object to import into the template as free variables.
|
14492 | * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
|
14493 | * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
|
14494 | * @param {string} [options.variable] The data object variable name.
|
14495 | * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
|
14496 | * @returns {Function} Returns the compiled template function.
|
14497 | * @example
|
14498 | *
|
14499 | * // using the "interpolate" delimiter to create a compiled template
|
14500 | * var compiled = _.template('hello <%= user %>!');
|
14501 | * compiled({ 'user': 'fred' });
|
14502 | * // => 'hello fred!'
|
14503 | *
|
14504 | * // using the HTML "escape" delimiter to escape data property values
|
14505 | * var compiled = _.template('<b><%- value %></b>');
|
14506 | * compiled({ 'value': '<script>' });
|
14507 | * // => '<b><script></b>'
|
14508 | *
|
14509 | * // using the "evaluate" delimiter to execute JavaScript and generate HTML
|
14510 | * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
|
14511 | * compiled({ 'users': ['fred', 'barney'] });
|
14512 | * // => '<li>fred</li><li>barney</li>'
|
14513 | *
|
14514 | * // using the internal `print` function in "evaluate" delimiters
|
14515 | * var compiled = _.template('<% print("hello " + user); %>!');
|
14516 | * compiled({ 'user': 'barney' });
|
14517 | * // => 'hello barney!'
|
14518 | *
|
14519 | * // using the ES delimiter as an alternative to the default "interpolate" delimiter
|
14520 | * var compiled = _.template('hello ${ user }!');
|
14521 | * compiled({ 'user': 'pebbles' });
|
14522 | * // => 'hello pebbles!'
|
14523 | *
|
14524 | * // using custom template delimiters
|
14525 | * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
|
14526 | * var compiled = _.template('hello {{ user }}!');
|
14527 | * compiled({ 'user': 'mustache' });
|
14528 | * // => 'hello mustache!'
|
14529 | *
|
14530 | * // using backslashes to treat delimiters as plain text
|
14531 | * var compiled = _.template('<%= "\\<%- value %\\>" %>');
|
14532 | * compiled({ 'value': 'ignored' });
|
14533 | * // => '<%- value %>'
|
14534 | *
|
14535 | * // using the `imports` option to import `jQuery` as `jq`
|
14536 | * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
|
14537 | * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
|
14538 | * compiled({ 'users': ['fred', 'barney'] });
|
14539 | * // => '<li>fred</li><li>barney</li>'
|
14540 | *
|
14541 | * // using the `sourceURL` option to specify a custom sourceURL for the template
|
14542 | * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
|
14543 | * compiled(data);
|
14544 | * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
|
14545 | *
|
14546 | * // using the `variable` option to ensure a with-statement isn't used in the compiled template
|
14547 | * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
|
14548 | * compiled.source;
|
14549 | * // => function(data) {
|
14550 | * // var __t, __p = '';
|
14551 | * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
|
14552 | * // return __p;
|
14553 | * // }
|
14554 | *
|
14555 | * // using the `source` property to inline compiled templates for meaningful
|
14556 | * // line numbers in error messages and a stack trace
|
14557 | * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
|
14558 | * var JST = {\
|
14559 | * "main": ' + _.template(mainText).source + '\
|
14560 | * };\
|
14561 | * ');
|
14562 | */
|
14563 | function template(string, options, otherOptions) {
|
14564 | // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
|
14565 | // and Laura Doktorova's doT.js (https://github.com/olado/doT).
|
14566 | var settings = lodash.templateSettings;
|
14567 |
|
14568 | if (otherOptions && isIterateeCall(string, options, otherOptions)) {
|
14569 | options = otherOptions = undefined;
|
14570 | }
|
14571 | string = baseToString(string);
|
14572 | options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
|
14573 |
|
14574 | var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
|
14575 | importsKeys = keys(imports),
|
14576 | importsValues = baseValues(imports, importsKeys);
|
14577 |
|
14578 | var isEscaping,
|
14579 | isEvaluating,
|
14580 | index = 0,
|
14581 | interpolate = options.interpolate || reNoMatch,
|
14582 | source = "__p += '";
|
14583 |
|
14584 | // Compile the regexp to match each delimiter.
|
14585 | var reDelimiters = RegExp(
|
14586 | (options.escape || reNoMatch).source + '|' +
|
14587 | interpolate.source + '|' +
|
14588 | (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
|
14589 | (options.evaluate || reNoMatch).source + '|$'
|
14590 | , 'g');
|
14591 |
|
14592 | // Use a sourceURL for easier debugging.
|
14593 | var sourceURL = '//# sourceURL=' +
|
14594 | ('sourceURL' in options
|
14595 | ? options.sourceURL
|
14596 | : ('lodash.templateSources[' + (++templateCounter) + ']')
|
14597 | ) + '\n';
|
14598 |
|
14599 | string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
|
14600 | interpolateValue || (interpolateValue = esTemplateValue);
|
14601 |
|
14602 | // Escape characters that can't be included in string literals.
|
14603 | source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
|
14604 |
|
14605 | // Replace delimiters with snippets.
|
14606 | if (escapeValue) {
|
14607 | isEscaping = true;
|
14608 | source += "' +\n__e(" + escapeValue + ") +\n'";
|
14609 | }
|
14610 | if (evaluateValue) {
|
14611 | isEvaluating = true;
|
14612 | source += "';\n" + evaluateValue + ";\n__p += '";
|
14613 | }
|
14614 | if (interpolateValue) {
|
14615 | source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
|
14616 | }
|
14617 | index = offset + match.length;
|
14618 |
|
14619 | // The JS engine embedded in Adobe products requires returning the `match`
|
14620 | // string in order to produce the correct `offset` value.
|
14621 | return match;
|
14622 | });
|
14623 |
|
14624 | source += "';\n";
|
14625 |
|
14626 | // If `variable` is not specified wrap a with-statement around the generated
|
14627 | // code to add the data object to the top of the scope chain.
|
14628 | var variable = options.variable;
|
14629 | if (!variable) {
|
14630 | source = 'with (obj) {\n' + source + '\n}\n';
|
14631 | }
|
14632 | // Cleanup code by stripping empty strings.
|
14633 | source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
|
14634 | .replace(reEmptyStringMiddle, '$1')
|
14635 | .replace(reEmptyStringTrailing, '$1;');
|
14636 |
|
14637 | // Frame code as the function body.
|
14638 | source = 'function(' + (variable || 'obj') + ') {\n' +
|
14639 | (variable
|
14640 | ? ''
|
14641 | : 'obj || (obj = {});\n'
|
14642 | ) +
|
14643 | "var __t, __p = ''" +
|
14644 | (isEscaping
|
14645 | ? ', __e = _.escape'
|
14646 | : ''
|
14647 | ) +
|
14648 | (isEvaluating
|
14649 | ? ', __j = Array.prototype.join;\n' +
|
14650 | "function print() { __p += __j.call(arguments, '') }\n"
|
14651 | : ';\n'
|
14652 | ) +
|
14653 | source +
|
14654 | 'return __p\n}';
|
14655 |
|
14656 | var result = attempt(function() {
|
14657 | return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
|
14658 | });
|
14659 |
|
14660 | // Provide the compiled function's source by its `toString` method or
|
14661 | // the `source` property as a convenience for inlining compiled templates.
|
14662 | result.source = source;
|
14663 | if (isError(result)) {
|
14664 | throw result;
|
14665 | }
|
14666 | return result;
|
14667 | }
|
14668 |
|
14669 | /**
|
14670 | * Removes leading and trailing whitespace or specified characters from `string`.
|
14671 | *
|
14672 | * @static
|
14673 | * @memberOf _
|
14674 | * @category String
|
14675 | * @param {string} [string=''] The string to trim.
|
14676 | * @param {string} [chars=whitespace] The characters to trim.
|
14677 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
14678 | * @returns {string} Returns the trimmed string.
|
14679 | * @example
|
14680 | *
|
14681 | * _.trim(' abc ');
|
14682 | * // => 'abc'
|
14683 | *
|
14684 | * _.trim('-_-abc-_-', '_-');
|
14685 | * // => 'abc'
|
14686 | *
|
14687 | * _.map([' foo ', ' bar '], _.trim);
|
14688 | * // => ['foo', 'bar']
|
14689 | */
|
14690 | function trim(string, chars, guard) {
|
14691 | var value = string;
|
14692 | string = baseToString(string);
|
14693 | if (!string) {
|
14694 | return string;
|
14695 | }
|
14696 | if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
|
14697 | return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
|
14698 | }
|
14699 | chars = (chars + '');
|
14700 | return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
|
14701 | }
|
14702 |
|
14703 | /**
|
14704 | * Removes leading whitespace or specified characters from `string`.
|
14705 | *
|
14706 | * @static
|
14707 | * @memberOf _
|
14708 | * @category String
|
14709 | * @param {string} [string=''] The string to trim.
|
14710 | * @param {string} [chars=whitespace] The characters to trim.
|
14711 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
14712 | * @returns {string} Returns the trimmed string.
|
14713 | * @example
|
14714 | *
|
14715 | * _.trimLeft(' abc ');
|
14716 | * // => 'abc '
|
14717 | *
|
14718 | * _.trimLeft('-_-abc-_-', '_-');
|
14719 | * // => 'abc-_-'
|
14720 | */
|
14721 | function trimLeft(string, chars, guard) {
|
14722 | var value = string;
|
14723 | string = baseToString(string);
|
14724 | if (!string) {
|
14725 | return string;
|
14726 | }
|
14727 | if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
|
14728 | return string.slice(trimmedLeftIndex(string));
|
14729 | }
|
14730 | return string.slice(charsLeftIndex(string, (chars + '')));
|
14731 | }
|
14732 |
|
14733 | /**
|
14734 | * Removes trailing whitespace or specified characters from `string`.
|
14735 | *
|
14736 | * @static
|
14737 | * @memberOf _
|
14738 | * @category String
|
14739 | * @param {string} [string=''] The string to trim.
|
14740 | * @param {string} [chars=whitespace] The characters to trim.
|
14741 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
14742 | * @returns {string} Returns the trimmed string.
|
14743 | * @example
|
14744 | *
|
14745 | * _.trimRight(' abc ');
|
14746 | * // => ' abc'
|
14747 | *
|
14748 | * _.trimRight('-_-abc-_-', '_-');
|
14749 | * // => '-_-abc'
|
14750 | */
|
14751 | function trimRight(string, chars, guard) {
|
14752 | var value = string;
|
14753 | string = baseToString(string);
|
14754 | if (!string) {
|
14755 | return string;
|
14756 | }
|
14757 | if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
|
14758 | return string.slice(0, trimmedRightIndex(string) + 1);
|
14759 | }
|
14760 | return string.slice(0, charsRightIndex(string, (chars + '')) + 1);
|
14761 | }
|
14762 |
|
14763 | /**
|
14764 | * Truncates `string` if it's longer than the given maximum string length.
|
14765 | * The last characters of the truncated string are replaced with the omission
|
14766 | * string which defaults to "...".
|
14767 | *
|
14768 | * @static
|
14769 | * @memberOf _
|
14770 | * @category String
|
14771 | * @param {string} [string=''] The string to truncate.
|
14772 | * @param {Object|number} [options] The options object or maximum string length.
|
14773 | * @param {number} [options.length=30] The maximum string length.
|
14774 | * @param {string} [options.omission='...'] The string to indicate text is omitted.
|
14775 | * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
|
14776 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
14777 | * @returns {string} Returns the truncated string.
|
14778 | * @example
|
14779 | *
|
14780 | * _.trunc('hi-diddly-ho there, neighborino');
|
14781 | * // => 'hi-diddly-ho there, neighbo...'
|
14782 | *
|
14783 | * _.trunc('hi-diddly-ho there, neighborino', 24);
|
14784 | * // => 'hi-diddly-ho there, n...'
|
14785 | *
|
14786 | * _.trunc('hi-diddly-ho there, neighborino', {
|
14787 | * 'length': 24,
|
14788 | * 'separator': ' '
|
14789 | * });
|
14790 | * // => 'hi-diddly-ho there,...'
|
14791 | *
|
14792 | * _.trunc('hi-diddly-ho there, neighborino', {
|
14793 | * 'length': 24,
|
14794 | * 'separator': /,? +/
|
14795 | * });
|
14796 | * // => 'hi-diddly-ho there...'
|
14797 | *
|
14798 | * _.trunc('hi-diddly-ho there, neighborino', {
|
14799 | * 'omission': ' [...]'
|
14800 | * });
|
14801 | * // => 'hi-diddly-ho there, neig [...]'
|
14802 | */
|
14803 | function trunc(string, options, guard) {
|
14804 | if (guard && isIterateeCall(string, options, guard)) {
|
14805 | options = undefined;
|
14806 | }
|
14807 | var length = DEFAULT_TRUNC_LENGTH,
|
14808 | omission = DEFAULT_TRUNC_OMISSION;
|
14809 |
|
14810 | if (options != null) {
|
14811 | if (isObject(options)) {
|
14812 | var separator = 'separator' in options ? options.separator : separator;
|
14813 | length = 'length' in options ? (+options.length || 0) : length;
|
14814 | omission = 'omission' in options ? baseToString(options.omission) : omission;
|
14815 | } else {
|
14816 | length = +options || 0;
|
14817 | }
|
14818 | }
|
14819 | string = baseToString(string);
|
14820 | if (length >= string.length) {
|
14821 | return string;
|
14822 | }
|
14823 | var end = length - omission.length;
|
14824 | if (end < 1) {
|
14825 | return omission;
|
14826 | }
|
14827 | var result = string.slice(0, end);
|
14828 | if (separator == null) {
|
14829 | return result + omission;
|
14830 | }
|
14831 | if (isRegExp(separator)) {
|
14832 | if (string.slice(end).search(separator)) {
|
14833 | var match,
|
14834 | newEnd,
|
14835 | substring = string.slice(0, end);
|
14836 |
|
14837 | if (!separator.global) {
|
14838 | separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
|
14839 | }
|
14840 | separator.lastIndex = 0;
|
14841 | while ((match = separator.exec(substring))) {
|
14842 | newEnd = match.index;
|
14843 | }
|
14844 | result = result.slice(0, newEnd == null ? end : newEnd);
|
14845 | }
|
14846 | } else if (string.indexOf(separator, end) != end) {
|
14847 | var index = result.lastIndexOf(separator);
|
14848 | if (index > -1) {
|
14849 | result = result.slice(0, index);
|
14850 | }
|
14851 | }
|
14852 | return result + omission;
|
14853 | }
|
14854 |
|
14855 | /**
|
14856 | * The inverse of `_.escape`; this method converts the HTML entities
|
14857 | * `&`, `<`, `>`, `"`, `'`, and ``` in `string` to their
|
14858 | * corresponding characters.
|
14859 | *
|
14860 | * **Note:** No other HTML entities are unescaped. To unescape additional HTML
|
14861 | * entities use a third-party library like [_he_](https://mths.be/he).
|
14862 | *
|
14863 | * @static
|
14864 | * @memberOf _
|
14865 | * @category String
|
14866 | * @param {string} [string=''] The string to unescape.
|
14867 | * @returns {string} Returns the unescaped string.
|
14868 | * @example
|
14869 | *
|
14870 | * _.unescape('fred, barney, & pebbles');
|
14871 | * // => 'fred, barney, & pebbles'
|
14872 | */
|
14873 | function unescape(string) {
|
14874 | string = baseToString(string);
|
14875 | return (string && reHasEscapedHtml.test(string))
|
14876 | ? string.replace(reEscapedHtml, unescapeHtmlChar)
|
14877 | : string;
|
14878 | }
|
14879 |
|
14880 | /**
|
14881 | * Splits `string` into an array of its words.
|
14882 | *
|
14883 | * @static
|
14884 | * @memberOf _
|
14885 | * @category String
|
14886 | * @param {string} [string=''] The string to inspect.
|
14887 | * @param {RegExp|string} [pattern] The pattern to match words.
|
14888 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
14889 | * @returns {Array} Returns the words of `string`.
|
14890 | * @example
|
14891 | *
|
14892 | * _.words('fred, barney, & pebbles');
|
14893 | * // => ['fred', 'barney', 'pebbles']
|
14894 | *
|
14895 | * _.words('fred, barney, & pebbles', /[^, ]+/g);
|
14896 | * // => ['fred', 'barney', '&', 'pebbles']
|
14897 | */
|
14898 | function words(string, pattern, guard) {
|
14899 | if (guard && isIterateeCall(string, pattern, guard)) {
|
14900 | pattern = undefined;
|
14901 | }
|
14902 | string = baseToString(string);
|
14903 | return string.match(pattern || reWords) || [];
|
14904 | }
|
14905 |
|
14906 | /*------------------------------------------------------------------------*/
|
14907 |
|
14908 | /**
|
14909 | * Attempts to invoke `func`, returning either the result or the caught error
|
14910 | * object. Any additional arguments are provided to `func` when it is invoked.
|
14911 | *
|
14912 | * @static
|
14913 | * @memberOf _
|
14914 | * @category Utility
|
14915 | * @param {Function} func The function to attempt.
|
14916 | * @returns {*} Returns the `func` result or error object.
|
14917 | * @example
|
14918 | *
|
14919 | * // avoid throwing errors for invalid selectors
|
14920 | * var elements = _.attempt(function(selector) {
|
14921 | * return document.querySelectorAll(selector);
|
14922 | * }, '>_>');
|
14923 | *
|
14924 | * if (_.isError(elements)) {
|
14925 | * elements = [];
|
14926 | * }
|
14927 | */
|
14928 | var attempt = restParam(function(func, args) {
|
14929 | try {
|
14930 | return func.apply(undefined, args);
|
14931 | } catch(e) {
|
14932 | return isError(e) ? e : new Error(e);
|
14933 | }
|
14934 | });
|
14935 |
|
14936 | /**
|
14937 | * Creates a function that invokes `func` with the `this` binding of `thisArg`
|
14938 | * and arguments of the created function. If `func` is a property name the
|
14939 | * created callback returns the property value for a given element. If `func`
|
14940 | * is an object the created callback returns `true` for elements that contain
|
14941 | * the equivalent object properties, otherwise it returns `false`.
|
14942 | *
|
14943 | * @static
|
14944 | * @memberOf _
|
14945 | * @alias iteratee
|
14946 | * @category Utility
|
14947 | * @param {*} [func=_.identity] The value to convert to a callback.
|
14948 | * @param {*} [thisArg] The `this` binding of `func`.
|
14949 | * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
|
14950 | * @returns {Function} Returns the callback.
|
14951 | * @example
|
14952 | *
|
14953 | * var users = [
|
14954 | * { 'user': 'barney', 'age': 36 },
|
14955 | * { 'user': 'fred', 'age': 40 }
|
14956 | * ];
|
14957 | *
|
14958 | * // wrap to create custom callback shorthands
|
14959 | * _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
|
14960 | * var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
|
14961 | * if (!match) {
|
14962 | * return callback(func, thisArg);
|
14963 | * }
|
14964 | * return function(object) {
|
14965 | * return match[2] == 'gt'
|
14966 | * ? object[match[1]] > match[3]
|
14967 | * : object[match[1]] < match[3];
|
14968 | * };
|
14969 | * });
|
14970 | *
|
14971 | * _.filter(users, 'age__gt36');
|
14972 | * // => [{ 'user': 'fred', 'age': 40 }]
|
14973 | */
|
14974 | function callback(func, thisArg, guard) {
|
14975 | if (guard && isIterateeCall(func, thisArg, guard)) {
|
14976 | thisArg = undefined;
|
14977 | }
|
14978 | return isObjectLike(func)
|
14979 | ? matches(func)
|
14980 | : baseCallback(func, thisArg);
|
14981 | }
|
14982 |
|
14983 | /**
|
14984 | * Creates a function that returns `value`.
|
14985 | *
|
14986 | * @static
|
14987 | * @memberOf _
|
14988 | * @category Utility
|
14989 | * @param {*} value The value to return from the new function.
|
14990 | * @returns {Function} Returns the new function.
|
14991 | * @example
|
14992 | *
|
14993 | * var object = { 'user': 'fred' };
|
14994 | * var getter = _.constant(object);
|
14995 | *
|
14996 | * getter() === object;
|
14997 | * // => true
|
14998 | */
|
14999 | function constant(value) {
|
15000 | return function() {
|
15001 | return value;
|
15002 | };
|
15003 | }
|
15004 |
|
15005 | /**
|
15006 | * This method returns the first argument provided to it.
|
15007 | *
|
15008 | * @static
|
15009 | * @memberOf _
|
15010 | * @category Utility
|
15011 | * @param {*} value Any value.
|
15012 | * @returns {*} Returns `value`.
|
15013 | * @example
|
15014 | *
|
15015 | * var object = { 'user': 'fred' };
|
15016 | *
|
15017 | * _.identity(object) === object;
|
15018 | * // => true
|
15019 | */
|
15020 | function identity(value) {
|
15021 | return value;
|
15022 | }
|
15023 |
|
15024 | /**
|
15025 | * Creates a function that performs a deep comparison between a given object
|
15026 | * and `source`, returning `true` if the given object has equivalent property
|
15027 | * values, else `false`.
|
15028 | *
|
15029 | * **Note:** This method supports comparing arrays, booleans, `Date` objects,
|
15030 | * numbers, `Object` objects, regexes, and strings. Objects are compared by
|
15031 | * their own, not inherited, enumerable properties. For comparing a single
|
15032 | * own or inherited property value see `_.matchesProperty`.
|
15033 | *
|
15034 | * @static
|
15035 | * @memberOf _
|
15036 | * @category Utility
|
15037 | * @param {Object} source The object of property values to match.
|
15038 | * @returns {Function} Returns the new function.
|
15039 | * @example
|
15040 | *
|
15041 | * var users = [
|
15042 | * { 'user': 'barney', 'age': 36, 'active': true },
|
15043 | * { 'user': 'fred', 'age': 40, 'active': false }
|
15044 | * ];
|
15045 | *
|
15046 | * _.filter(users, _.matches({ 'age': 40, 'active': false }));
|
15047 | * // => [{ 'user': 'fred', 'age': 40, 'active': false }]
|
15048 | */
|
15049 | function matches(source) {
|
15050 | return baseMatches(baseClone(source, true));
|
15051 | }
|
15052 |
|
15053 | /**
|
15054 | * Creates a function that compares the property value of `path` on a given
|
15055 | * object to `value`.
|
15056 | *
|
15057 | * **Note:** This method supports comparing arrays, booleans, `Date` objects,
|
15058 | * numbers, `Object` objects, regexes, and strings. Objects are compared by
|
15059 | * their own, not inherited, enumerable properties.
|
15060 | *
|
15061 | * @static
|
15062 | * @memberOf _
|
15063 | * @category Utility
|
15064 | * @param {Array|string} path The path of the property to get.
|
15065 | * @param {*} srcValue The value to match.
|
15066 | * @returns {Function} Returns the new function.
|
15067 | * @example
|
15068 | *
|
15069 | * var users = [
|
15070 | * { 'user': 'barney' },
|
15071 | * { 'user': 'fred' }
|
15072 | * ];
|
15073 | *
|
15074 | * _.find(users, _.matchesProperty('user', 'fred'));
|
15075 | * // => { 'user': 'fred' }
|
15076 | */
|
15077 | function matchesProperty(path, srcValue) {
|
15078 | return baseMatchesProperty(path, baseClone(srcValue, true));
|
15079 | }
|
15080 |
|
15081 | /**
|
15082 | * Creates a function that invokes the method at `path` on a given object.
|
15083 | * Any additional arguments are provided to the invoked method.
|
15084 | *
|
15085 | * @static
|
15086 | * @memberOf _
|
15087 | * @category Utility
|
15088 | * @param {Array|string} path The path of the method to invoke.
|
15089 | * @param {...*} [args] The arguments to invoke the method with.
|
15090 | * @returns {Function} Returns the new function.
|
15091 | * @example
|
15092 | *
|
15093 | * var objects = [
|
15094 | * { 'a': { 'b': { 'c': _.constant(2) } } },
|
15095 | * { 'a': { 'b': { 'c': _.constant(1) } } }
|
15096 | * ];
|
15097 | *
|
15098 | * _.map(objects, _.method('a.b.c'));
|
15099 | * // => [2, 1]
|
15100 | *
|
15101 | * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
|
15102 | * // => [1, 2]
|
15103 | */
|
15104 | var method = restParam(function(path, args) {
|
15105 | return function(object) {
|
15106 | return invokePath(object, path, args);
|
15107 | };
|
15108 | });
|
15109 |
|
15110 | /**
|
15111 | * The opposite of `_.method`; this method creates a function that invokes
|
15112 | * the method at a given path on `object`. Any additional arguments are
|
15113 | * provided to the invoked method.
|
15114 | *
|
15115 | * @static
|
15116 | * @memberOf _
|
15117 | * @category Utility
|
15118 | * @param {Object} object The object to query.
|
15119 | * @param {...*} [args] The arguments to invoke the method with.
|
15120 | * @returns {Function} Returns the new function.
|
15121 | * @example
|
15122 | *
|
15123 | * var array = _.times(3, _.constant),
|
15124 | * object = { 'a': array, 'b': array, 'c': array };
|
15125 | *
|
15126 | * _.map(['a[2]', 'c[0]'], _.methodOf(object));
|
15127 | * // => [2, 0]
|
15128 | *
|
15129 | * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
|
15130 | * // => [2, 0]
|
15131 | */
|
15132 | var methodOf = restParam(function(object, args) {
|
15133 | return function(path) {
|
15134 | return invokePath(object, path, args);
|
15135 | };
|
15136 | });
|
15137 |
|
15138 | /**
|
15139 | * Adds all own enumerable function properties of a source object to the
|
15140 | * destination object. If `object` is a function then methods are added to
|
15141 | * its prototype as well.
|
15142 | *
|
15143 | * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
|
15144 | * avoid conflicts caused by modifying the original.
|
15145 | *
|
15146 | * @static
|
15147 | * @memberOf _
|
15148 | * @category Utility
|
15149 | * @param {Function|Object} [object=lodash] The destination object.
|
15150 | * @param {Object} source The object of functions to add.
|
15151 | * @param {Object} [options] The options object.
|
15152 | * @param {boolean} [options.chain=true] Specify whether the functions added
|
15153 | * are chainable.
|
15154 | * @returns {Function|Object} Returns `object`.
|
15155 | * @example
|
15156 | *
|
15157 | * function vowels(string) {
|
15158 | * return _.filter(string, function(v) {
|
15159 | * return /[aeiou]/i.test(v);
|
15160 | * });
|
15161 | * }
|
15162 | *
|
15163 | * _.mixin({ 'vowels': vowels });
|
15164 | * _.vowels('fred');
|
15165 | * // => ['e']
|
15166 | *
|
15167 | * _('fred').vowels().value();
|
15168 | * // => ['e']
|
15169 | *
|
15170 | * _.mixin({ 'vowels': vowels }, { 'chain': false });
|
15171 | * _('fred').vowels();
|
15172 | * // => ['e']
|
15173 | */
|
15174 | function mixin(object, source, options) {
|
15175 | if (options == null) {
|
15176 | var isObj = isObject(source),
|
15177 | props = isObj ? keys(source) : undefined,
|
15178 | methodNames = (props && props.length) ? baseFunctions(source, props) : undefined;
|
15179 |
|
15180 | if (!(methodNames ? methodNames.length : isObj)) {
|
15181 | methodNames = false;
|
15182 | options = source;
|
15183 | source = object;
|
15184 | object = this;
|
15185 | }
|
15186 | }
|
15187 | if (!methodNames) {
|
15188 | methodNames = baseFunctions(source, keys(source));
|
15189 | }
|
15190 | var chain = true,
|
15191 | index = -1,
|
15192 | isFunc = isFunction(object),
|
15193 | length = methodNames.length;
|
15194 |
|
15195 | if (options === false) {
|
15196 | chain = false;
|
15197 | } else if (isObject(options) && 'chain' in options) {
|
15198 | chain = options.chain;
|
15199 | }
|
15200 | while (++index < length) {
|
15201 | var methodName = methodNames[index],
|
15202 | func = source[methodName];
|
15203 |
|
15204 | object[methodName] = func;
|
15205 | if (isFunc) {
|
15206 | object.prototype[methodName] = (function(func) {
|
15207 | return function() {
|
15208 | var chainAll = this.__chain__;
|
15209 | if (chain || chainAll) {
|
15210 | var result = object(this.__wrapped__),
|
15211 | actions = result.__actions__ = arrayCopy(this.__actions__);
|
15212 |
|
15213 | actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
|
15214 | result.__chain__ = chainAll;
|
15215 | return result;
|
15216 | }
|
15217 | return func.apply(object, arrayPush([this.value()], arguments));
|
15218 | };
|
15219 | }(func));
|
15220 | }
|
15221 | }
|
15222 | return object;
|
15223 | }
|
15224 |
|
15225 | /**
|
15226 | * Reverts the `_` variable to its previous value and returns a reference to
|
15227 | * the `lodash` function.
|
15228 | *
|
15229 | * @static
|
15230 | * @memberOf _
|
15231 | * @category Utility
|
15232 | * @returns {Function} Returns the `lodash` function.
|
15233 | * @example
|
15234 | *
|
15235 | * var lodash = _.noConflict();
|
15236 | */
|
15237 | function noConflict() {
|
15238 | root._ = oldDash;
|
15239 | return this;
|
15240 | }
|
15241 |
|
15242 | /**
|
15243 | * A no-operation function that returns `undefined` regardless of the
|
15244 | * arguments it receives.
|
15245 | *
|
15246 | * @static
|
15247 | * @memberOf _
|
15248 | * @category Utility
|
15249 | * @example
|
15250 | *
|
15251 | * var object = { 'user': 'fred' };
|
15252 | *
|
15253 | * _.noop(object) === undefined;
|
15254 | * // => true
|
15255 | */
|
15256 | function noop() {
|
15257 | // No operation performed.
|
15258 | }
|
15259 |
|
15260 | /**
|
15261 | * Creates a function that returns the property value at `path` on a
|
15262 | * given object.
|
15263 | *
|
15264 | * @static
|
15265 | * @memberOf _
|
15266 | * @category Utility
|
15267 | * @param {Array|string} path The path of the property to get.
|
15268 | * @returns {Function} Returns the new function.
|
15269 | * @example
|
15270 | *
|
15271 | * var objects = [
|
15272 | * { 'a': { 'b': { 'c': 2 } } },
|
15273 | * { 'a': { 'b': { 'c': 1 } } }
|
15274 | * ];
|
15275 | *
|
15276 | * _.map(objects, _.property('a.b.c'));
|
15277 | * // => [2, 1]
|
15278 | *
|
15279 | * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
|
15280 | * // => [1, 2]
|
15281 | */
|
15282 | function property(path) {
|
15283 | return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
|
15284 | }
|
15285 |
|
15286 | /**
|
15287 | * The opposite of `_.property`; this method creates a function that returns
|
15288 | * the property value at a given path on `object`.
|
15289 | *
|
15290 | * @static
|
15291 | * @memberOf _
|
15292 | * @category Utility
|
15293 | * @param {Object} object The object to query.
|
15294 | * @returns {Function} Returns the new function.
|
15295 | * @example
|
15296 | *
|
15297 | * var array = [0, 1, 2],
|
15298 | * object = { 'a': array, 'b': array, 'c': array };
|
15299 | *
|
15300 | * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
|
15301 | * // => [2, 0]
|
15302 | *
|
15303 | * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
|
15304 | * // => [2, 0]
|
15305 | */
|
15306 | function propertyOf(object) {
|
15307 | return function(path) {
|
15308 | return baseGet(object, toPath(path), path + '');
|
15309 | };
|
15310 | }
|
15311 |
|
15312 | /**
|
15313 | * Creates an array of numbers (positive and/or negative) progressing from
|
15314 | * `start` up to, but not including, `end`. If `end` is not specified it is
|
15315 | * set to `start` with `start` then set to `0`. If `end` is less than `start`
|
15316 | * a zero-length range is created unless a negative `step` is specified.
|
15317 | *
|
15318 | * @static
|
15319 | * @memberOf _
|
15320 | * @category Utility
|
15321 | * @param {number} [start=0] The start of the range.
|
15322 | * @param {number} end The end of the range.
|
15323 | * @param {number} [step=1] The value to increment or decrement by.
|
15324 | * @returns {Array} Returns the new array of numbers.
|
15325 | * @example
|
15326 | *
|
15327 | * _.range(4);
|
15328 | * // => [0, 1, 2, 3]
|
15329 | *
|
15330 | * _.range(1, 5);
|
15331 | * // => [1, 2, 3, 4]
|
15332 | *
|
15333 | * _.range(0, 20, 5);
|
15334 | * // => [0, 5, 10, 15]
|
15335 | *
|
15336 | * _.range(0, -4, -1);
|
15337 | * // => [0, -1, -2, -3]
|
15338 | *
|
15339 | * _.range(1, 4, 0);
|
15340 | * // => [1, 1, 1]
|
15341 | *
|
15342 | * _.range(0);
|
15343 | * // => []
|
15344 | */
|
15345 | function range(start, end, step) {
|
15346 | if (step && isIterateeCall(start, end, step)) {
|
15347 | end = step = undefined;
|
15348 | }
|
15349 | start = +start || 0;
|
15350 | step = step == null ? 1 : (+step || 0);
|
15351 |
|
15352 | if (end == null) {
|
15353 | end = start;
|
15354 | start = 0;
|
15355 | } else {
|
15356 | end = +end || 0;
|
15357 | }
|
15358 | // Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
|
15359 | // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
|
15360 | var index = -1,
|
15361 | length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
|
15362 | result = Array(length);
|
15363 |
|
15364 | while (++index < length) {
|
15365 | result[index] = start;
|
15366 | start += step;
|
15367 | }
|
15368 | return result;
|
15369 | }
|
15370 |
|
15371 | /**
|
15372 | * Invokes the iteratee function `n` times, returning an array of the results
|
15373 | * of each invocation. The `iteratee` is bound to `thisArg` and invoked with
|
15374 | * one argument; (index).
|
15375 | *
|
15376 | * @static
|
15377 | * @memberOf _
|
15378 | * @category Utility
|
15379 | * @param {number} n The number of times to invoke `iteratee`.
|
15380 | * @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
15381 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
15382 | * @returns {Array} Returns the array of results.
|
15383 | * @example
|
15384 | *
|
15385 | * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
|
15386 | * // => [3, 6, 4]
|
15387 | *
|
15388 | * _.times(3, function(n) {
|
15389 | * mage.castSpell(n);
|
15390 | * });
|
15391 | * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
|
15392 | *
|
15393 | * _.times(3, function(n) {
|
15394 | * this.cast(n);
|
15395 | * }, mage);
|
15396 | * // => also invokes `mage.castSpell(n)` three times
|
15397 | */
|
15398 | function times(n, iteratee, thisArg) {
|
15399 | n = nativeFloor(n);
|
15400 |
|
15401 | // Exit early to avoid a JSC JIT bug in Safari 8
|
15402 | // where `Array(0)` is treated as `Array(1)`.
|
15403 | if (n < 1 || !nativeIsFinite(n)) {
|
15404 | return [];
|
15405 | }
|
15406 | var index = -1,
|
15407 | result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
|
15408 |
|
15409 | iteratee = bindCallback(iteratee, thisArg, 1);
|
15410 | while (++index < n) {
|
15411 | if (index < MAX_ARRAY_LENGTH) {
|
15412 | result[index] = iteratee(index);
|
15413 | } else {
|
15414 | iteratee(index);
|
15415 | }
|
15416 | }
|
15417 | return result;
|
15418 | }
|
15419 |
|
15420 | /**
|
15421 | * Generates a unique ID. If `prefix` is provided the ID is appended to it.
|
15422 | *
|
15423 | * @static
|
15424 | * @memberOf _
|
15425 | * @category Utility
|
15426 | * @param {string} [prefix] The value to prefix the ID with.
|
15427 | * @returns {string} Returns the unique ID.
|
15428 | * @example
|
15429 | *
|
15430 | * _.uniqueId('contact_');
|
15431 | * // => 'contact_104'
|
15432 | *
|
15433 | * _.uniqueId();
|
15434 | * // => '105'
|
15435 | */
|
15436 | function uniqueId(prefix) {
|
15437 | var id = ++idCounter;
|
15438 | return baseToString(prefix) + id;
|
15439 | }
|
15440 |
|
15441 | /*------------------------------------------------------------------------*/
|
15442 |
|
15443 | /**
|
15444 | * Adds two numbers.
|
15445 | *
|
15446 | * @static
|
15447 | * @memberOf _
|
15448 | * @category Math
|
15449 | * @param {number} augend The first number to add.
|
15450 | * @param {number} addend The second number to add.
|
15451 | * @returns {number} Returns the sum.
|
15452 | * @example
|
15453 | *
|
15454 | * _.add(6, 4);
|
15455 | * // => 10
|
15456 | */
|
15457 | function add(augend, addend) {
|
15458 | return (+augend || 0) + (+addend || 0);
|
15459 | }
|
15460 |
|
15461 | /**
|
15462 | * Calculates `n` rounded up to `precision`.
|
15463 | *
|
15464 | * @static
|
15465 | * @memberOf _
|
15466 | * @category Math
|
15467 | * @param {number} n The number to round up.
|
15468 | * @param {number} [precision=0] The precision to round up to.
|
15469 | * @returns {number} Returns the rounded up number.
|
15470 | * @example
|
15471 | *
|
15472 | * _.ceil(4.006);
|
15473 | * // => 5
|
15474 | *
|
15475 | * _.ceil(6.004, 2);
|
15476 | * // => 6.01
|
15477 | *
|
15478 | * _.ceil(6040, -2);
|
15479 | * // => 6100
|
15480 | */
|
15481 | var ceil = createRound('ceil');
|
15482 |
|
15483 | /**
|
15484 | * Calculates `n` rounded down to `precision`.
|
15485 | *
|
15486 | * @static
|
15487 | * @memberOf _
|
15488 | * @category Math
|
15489 | * @param {number} n The number to round down.
|
15490 | * @param {number} [precision=0] The precision to round down to.
|
15491 | * @returns {number} Returns the rounded down number.
|
15492 | * @example
|
15493 | *
|
15494 | * _.floor(4.006);
|
15495 | * // => 4
|
15496 | *
|
15497 | * _.floor(0.046, 2);
|
15498 | * // => 0.04
|
15499 | *
|
15500 | * _.floor(4060, -2);
|
15501 | * // => 4000
|
15502 | */
|
15503 | var floor = createRound('floor');
|
15504 |
|
15505 | /**
|
15506 | * Gets the maximum value of `collection`. If `collection` is empty or falsey
|
15507 | * `-Infinity` is returned. If an iteratee function is provided it is invoked
|
15508 | * for each value in `collection` to generate the criterion by which the value
|
15509 | * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
|
15510 | * arguments: (value, index, collection).
|
15511 | *
|
15512 | * If a property name is provided for `iteratee` the created `_.property`
|
15513 | * style callback returns the property value of the given element.
|
15514 | *
|
15515 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
15516 | * style callback returns `true` for elements that have a matching property
|
15517 | * value, else `false`.
|
15518 | *
|
15519 | * If an object is provided for `iteratee` the created `_.matches` style
|
15520 | * callback returns `true` for elements that have the properties of the given
|
15521 | * object, else `false`.
|
15522 | *
|
15523 | * @static
|
15524 | * @memberOf _
|
15525 | * @category Math
|
15526 | * @param {Array|Object|string} collection The collection to iterate over.
|
15527 | * @param {Function|Object|string} [iteratee] The function invoked per iteration.
|
15528 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
15529 | * @returns {*} Returns the maximum value.
|
15530 | * @example
|
15531 | *
|
15532 | * _.max([4, 2, 8, 6]);
|
15533 | * // => 8
|
15534 | *
|
15535 | * _.max([]);
|
15536 | * // => -Infinity
|
15537 | *
|
15538 | * var users = [
|
15539 | * { 'user': 'barney', 'age': 36 },
|
15540 | * { 'user': 'fred', 'age': 40 }
|
15541 | * ];
|
15542 | *
|
15543 | * _.max(users, function(chr) {
|
15544 | * return chr.age;
|
15545 | * });
|
15546 | * // => { 'user': 'fred', 'age': 40 }
|
15547 | *
|
15548 | * // using the `_.property` callback shorthand
|
15549 | * _.max(users, 'age');
|
15550 | * // => { 'user': 'fred', 'age': 40 }
|
15551 | */
|
15552 | var max = createExtremum(gt, NEGATIVE_INFINITY);
|
15553 |
|
15554 | /**
|
15555 | * Gets the minimum value of `collection`. If `collection` is empty or falsey
|
15556 | * `Infinity` is returned. If an iteratee function is provided it is invoked
|
15557 | * for each value in `collection` to generate the criterion by which the value
|
15558 | * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
|
15559 | * arguments: (value, index, collection).
|
15560 | *
|
15561 | * If a property name is provided for `iteratee` the created `_.property`
|
15562 | * style callback returns the property value of the given element.
|
15563 | *
|
15564 | * If a value is also provided for `thisArg` the created `_.matchesProperty`
|
15565 | * style callback returns `true` for elements that have a matching property
|
15566 | * value, else `false`.
|
15567 | *
|
15568 | * If an object is provided for `iteratee` the created `_.matches` style
|
15569 | * callback returns `true` for elements that have the properties of the given
|
15570 | * object, else `false`.
|
15571 | *
|
15572 | * @static
|
15573 | * @memberOf _
|
15574 | * @category Math
|
15575 | * @param {Array|Object|string} collection The collection to iterate over.
|
15576 | * @param {Function|Object|string} [iteratee] The function invoked per iteration.
|
15577 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
15578 | * @returns {*} Returns the minimum value.
|
15579 | * @example
|
15580 | *
|
15581 | * _.min([4, 2, 8, 6]);
|
15582 | * // => 2
|
15583 | *
|
15584 | * _.min([]);
|
15585 | * // => Infinity
|
15586 | *
|
15587 | * var users = [
|
15588 | * { 'user': 'barney', 'age': 36 },
|
15589 | * { 'user': 'fred', 'age': 40 }
|
15590 | * ];
|
15591 | *
|
15592 | * _.min(users, function(chr) {
|
15593 | * return chr.age;
|
15594 | * });
|
15595 | * // => { 'user': 'barney', 'age': 36 }
|
15596 | *
|
15597 | * // using the `_.property` callback shorthand
|
15598 | * _.min(users, 'age');
|
15599 | * // => { 'user': 'barney', 'age': 36 }
|
15600 | */
|
15601 | var min = createExtremum(lt, POSITIVE_INFINITY);
|
15602 |
|
15603 | /**
|
15604 | * Calculates `n` rounded to `precision`.
|
15605 | *
|
15606 | * @static
|
15607 | * @memberOf _
|
15608 | * @category Math
|
15609 | * @param {number} n The number to round.
|
15610 | * @param {number} [precision=0] The precision to round to.
|
15611 | * @returns {number} Returns the rounded number.
|
15612 | * @example
|
15613 | *
|
15614 | * _.round(4.006);
|
15615 | * // => 4
|
15616 | *
|
15617 | * _.round(4.006, 2);
|
15618 | * // => 4.01
|
15619 | *
|
15620 | * _.round(4060, -2);
|
15621 | * // => 4100
|
15622 | */
|
15623 | var round = createRound('round');
|
15624 |
|
15625 | /**
|
15626 | * Gets the sum of the values in `collection`.
|
15627 | *
|
15628 | * @static
|
15629 | * @memberOf _
|
15630 | * @category Math
|
15631 | * @param {Array|Object|string} collection The collection to iterate over.
|
15632 | * @param {Function|Object|string} [iteratee] The function invoked per iteration.
|
15633 | * @param {*} [thisArg] The `this` binding of `iteratee`.
|
15634 | * @returns {number} Returns the sum.
|
15635 | * @example
|
15636 | *
|
15637 | * _.sum([4, 6]);
|
15638 | * // => 10
|
15639 | *
|
15640 | * _.sum({ 'a': 4, 'b': 6 });
|
15641 | * // => 10
|
15642 | *
|
15643 | * var objects = [
|
15644 | * { 'n': 4 },
|
15645 | * { 'n': 6 }
|
15646 | * ];
|
15647 | *
|
15648 | * _.sum(objects, function(object) {
|
15649 | * return object.n;
|
15650 | * });
|
15651 | * // => 10
|
15652 | *
|
15653 | * // using the `_.property` callback shorthand
|
15654 | * _.sum(objects, 'n');
|
15655 | * // => 10
|
15656 | */
|
15657 | function sum(collection, iteratee, thisArg) {
|
15658 | if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
|
15659 | iteratee = undefined;
|
15660 | }
|
15661 | iteratee = getCallback(iteratee, thisArg, 3);
|
15662 | return iteratee.length == 1
|
15663 | ? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee)
|
15664 | : baseSum(collection, iteratee);
|
15665 | }
|
15666 |
|
15667 | /*------------------------------------------------------------------------*/
|
15668 |
|
15669 | // Ensure wrappers are instances of `baseLodash`.
|
15670 | lodash.prototype = baseLodash.prototype;
|
15671 |
|
15672 | LodashWrapper.prototype = baseCreate(baseLodash.prototype);
|
15673 | LodashWrapper.prototype.constructor = LodashWrapper;
|
15674 |
|
15675 | LazyWrapper.prototype = baseCreate(baseLodash.prototype);
|
15676 | LazyWrapper.prototype.constructor = LazyWrapper;
|
15677 |
|
15678 | // Add functions to the `Map` cache.
|
15679 | MapCache.prototype['delete'] = mapDelete;
|
15680 | MapCache.prototype.get = mapGet;
|
15681 | MapCache.prototype.has = mapHas;
|
15682 | MapCache.prototype.set = mapSet;
|
15683 |
|
15684 | // Add functions to the `Set` cache.
|
15685 | SetCache.prototype.push = cachePush;
|
15686 |
|
15687 | // Assign cache to `_.memoize`.
|
15688 | memoize.Cache = MapCache;
|
15689 |
|
15690 | // Add functions that return wrapped values when chaining.
|
15691 | lodash.after = after;
|
15692 | lodash.ary = ary;
|
15693 | lodash.assign = assign;
|
15694 | lodash.at = at;
|
15695 | lodash.before = before;
|
15696 | lodash.bind = bind;
|
15697 | lodash.bindAll = bindAll;
|
15698 | lodash.bindKey = bindKey;
|
15699 | lodash.callback = callback;
|
15700 | lodash.chain = chain;
|
15701 | lodash.chunk = chunk;
|
15702 | lodash.compact = compact;
|
15703 | lodash.constant = constant;
|
15704 | lodash.countBy = countBy;
|
15705 | lodash.create = create;
|
15706 | lodash.curry = curry;
|
15707 | lodash.curryRight = curryRight;
|
15708 | lodash.debounce = debounce;
|
15709 | lodash.defaults = defaults;
|
15710 | lodash.defaultsDeep = defaultsDeep;
|
15711 | lodash.defer = defer;
|
15712 | lodash.delay = delay;
|
15713 | lodash.difference = difference;
|
15714 | lodash.drop = drop;
|
15715 | lodash.dropRight = dropRight;
|
15716 | lodash.dropRightWhile = dropRightWhile;
|
15717 | lodash.dropWhile = dropWhile;
|
15718 | lodash.fill = fill;
|
15719 | lodash.filter = filter;
|
15720 | lodash.flatten = flatten;
|
15721 | lodash.flattenDeep = flattenDeep;
|
15722 | lodash.flow = flow;
|
15723 | lodash.flowRight = flowRight;
|
15724 | lodash.forEach = forEach;
|
15725 | lodash.forEachRight = forEachRight;
|
15726 | lodash.forIn = forIn;
|
15727 | lodash.forInRight = forInRight;
|
15728 | lodash.forOwn = forOwn;
|
15729 | lodash.forOwnRight = forOwnRight;
|
15730 | lodash.functions = functions;
|
15731 | lodash.groupBy = groupBy;
|
15732 | lodash.indexBy = indexBy;
|
15733 | lodash.initial = initial;
|
15734 | lodash.intersection = intersection;
|
15735 | lodash.invert = invert;
|
15736 | lodash.invoke = invoke;
|
15737 | lodash.keys = keys;
|
15738 | lodash.keysIn = keysIn;
|
15739 | lodash.map = map;
|
15740 | lodash.mapKeys = mapKeys;
|
15741 | lodash.mapValues = mapValues;
|
15742 | lodash.matches = matches;
|
15743 | lodash.matchesProperty = matchesProperty;
|
15744 | lodash.memoize = memoize;
|
15745 | lodash.merge = merge;
|
15746 | lodash.method = method;
|
15747 | lodash.methodOf = methodOf;
|
15748 | lodash.mixin = mixin;
|
15749 | lodash.modArgs = modArgs;
|
15750 | lodash.negate = negate;
|
15751 | lodash.omit = omit;
|
15752 | lodash.once = once;
|
15753 | lodash.pairs = pairs;
|
15754 | lodash.partial = partial;
|
15755 | lodash.partialRight = partialRight;
|
15756 | lodash.partition = partition;
|
15757 | lodash.pick = pick;
|
15758 | lodash.pluck = pluck;
|
15759 | lodash.property = property;
|
15760 | lodash.propertyOf = propertyOf;
|
15761 | lodash.pull = pull;
|
15762 | lodash.pullAt = pullAt;
|
15763 | lodash.range = range;
|
15764 | lodash.rearg = rearg;
|
15765 | lodash.reject = reject;
|
15766 | lodash.remove = remove;
|
15767 | lodash.rest = rest;
|
15768 | lodash.restParam = restParam;
|
15769 | lodash.set = set;
|
15770 | lodash.shuffle = shuffle;
|
15771 | lodash.slice = slice;
|
15772 | lodash.sortBy = sortBy;
|
15773 | lodash.sortByAll = sortByAll;
|
15774 | lodash.sortByOrder = sortByOrder;
|
15775 | lodash.spread = spread;
|
15776 | lodash.take = take;
|
15777 | lodash.takeRight = takeRight;
|
15778 | lodash.takeRightWhile = takeRightWhile;
|
15779 | lodash.takeWhile = takeWhile;
|
15780 | lodash.tap = tap;
|
15781 | lodash.throttle = throttle;
|
15782 | lodash.thru = thru;
|
15783 | lodash.times = times;
|
15784 | lodash.toArray = toArray;
|
15785 | lodash.toPlainObject = toPlainObject;
|
15786 | lodash.transform = transform;
|
15787 | lodash.union = union;
|
15788 | lodash.uniq = uniq;
|
15789 | lodash.unzip = unzip;
|
15790 | lodash.unzipWith = unzipWith;
|
15791 | lodash.values = values;
|
15792 | lodash.valuesIn = valuesIn;
|
15793 | lodash.where = where;
|
15794 | lodash.without = without;
|
15795 | lodash.wrap = wrap;
|
15796 | lodash.xor = xor;
|
15797 | lodash.zip = zip;
|
15798 | lodash.zipObject = zipObject;
|
15799 | lodash.zipWith = zipWith;
|
15800 |
|
15801 | // Add aliases.
|
15802 | lodash.backflow = flowRight;
|
15803 | lodash.collect = map;
|
15804 | lodash.compose = flowRight;
|
15805 | lodash.each = forEach;
|
15806 | lodash.eachRight = forEachRight;
|
15807 | lodash.extend = assign;
|
15808 | lodash.iteratee = callback;
|
15809 | lodash.methods = functions;
|
15810 | lodash.object = zipObject;
|
15811 | lodash.select = filter;
|
15812 | lodash.tail = rest;
|
15813 | lodash.unique = uniq;
|
15814 |
|
15815 | // Add functions to `lodash.prototype`.
|
15816 | mixin(lodash, lodash);
|
15817 |
|
15818 | /*------------------------------------------------------------------------*/
|
15819 |
|
15820 | // Add functions that return unwrapped values when chaining.
|
15821 | lodash.add = add;
|
15822 | lodash.attempt = attempt;
|
15823 | lodash.camelCase = camelCase;
|
15824 | lodash.capitalize = capitalize;
|
15825 | lodash.ceil = ceil;
|
15826 | lodash.clone = clone;
|
15827 | lodash.cloneDeep = cloneDeep;
|
15828 | lodash.deburr = deburr;
|
15829 | lodash.endsWith = endsWith;
|
15830 | lodash.escape = escape;
|
15831 | lodash.escapeRegExp = escapeRegExp;
|
15832 | lodash.every = every;
|
15833 | lodash.find = find;
|
15834 | lodash.findIndex = findIndex;
|
15835 | lodash.findKey = findKey;
|
15836 | lodash.findLast = findLast;
|
15837 | lodash.findLastIndex = findLastIndex;
|
15838 | lodash.findLastKey = findLastKey;
|
15839 | lodash.findWhere = findWhere;
|
15840 | lodash.first = first;
|
15841 | lodash.floor = floor;
|
15842 | lodash.get = get;
|
15843 | lodash.gt = gt;
|
15844 | lodash.gte = gte;
|
15845 | lodash.has = has;
|
15846 | lodash.identity = identity;
|
15847 | lodash.includes = includes;
|
15848 | lodash.indexOf = indexOf;
|
15849 | lodash.inRange = inRange;
|
15850 | lodash.isArguments = isArguments;
|
15851 | lodash.isArray = isArray;
|
15852 | lodash.isBoolean = isBoolean;
|
15853 | lodash.isDate = isDate;
|
15854 | lodash.isElement = isElement;
|
15855 | lodash.isEmpty = isEmpty;
|
15856 | lodash.isEqual = isEqual;
|
15857 | lodash.isError = isError;
|
15858 | lodash.isFinite = isFinite;
|
15859 | lodash.isFunction = isFunction;
|
15860 | lodash.isMatch = isMatch;
|
15861 | lodash.isNaN = isNaN;
|
15862 | lodash.isNative = isNative;
|
15863 | lodash.isNull = isNull;
|
15864 | lodash.isNumber = isNumber;
|
15865 | lodash.isObject = isObject;
|
15866 | lodash.isPlainObject = isPlainObject;
|
15867 | lodash.isRegExp = isRegExp;
|
15868 | lodash.isString = isString;
|
15869 | lodash.isTypedArray = isTypedArray;
|
15870 | lodash.isUndefined = isUndefined;
|
15871 | lodash.kebabCase = kebabCase;
|
15872 | lodash.last = last;
|
15873 | lodash.lastIndexOf = lastIndexOf;
|
15874 | lodash.lt = lt;
|
15875 | lodash.lte = lte;
|
15876 | lodash.max = max;
|
15877 | lodash.min = min;
|
15878 | lodash.noConflict = noConflict;
|
15879 | lodash.noop = noop;
|
15880 | lodash.now = now;
|
15881 | lodash.pad = pad;
|
15882 | lodash.padLeft = padLeft;
|
15883 | lodash.padRight = padRight;
|
15884 | lodash.parseInt = parseInt;
|
15885 | lodash.random = random;
|
15886 | lodash.reduce = reduce;
|
15887 | lodash.reduceRight = reduceRight;
|
15888 | lodash.repeat = repeat;
|
15889 | lodash.result = result;
|
15890 | lodash.round = round;
|
15891 | lodash.runInContext = runInContext;
|
15892 | lodash.size = size;
|
15893 | lodash.snakeCase = snakeCase;
|
15894 | lodash.some = some;
|
15895 | lodash.sortedIndex = sortedIndex;
|
15896 | lodash.sortedLastIndex = sortedLastIndex;
|
15897 | lodash.startCase = startCase;
|
15898 | lodash.startsWith = startsWith;
|
15899 | lodash.sum = sum;
|
15900 | lodash.template = template;
|
15901 | lodash.trim = trim;
|
15902 | lodash.trimLeft = trimLeft;
|
15903 | lodash.trimRight = trimRight;
|
15904 | lodash.trunc = trunc;
|
15905 | lodash.unescape = unescape;
|
15906 | lodash.uniqueId = uniqueId;
|
15907 | lodash.words = words;
|
15908 |
|
15909 | // Add aliases.
|
15910 | lodash.all = every;
|
15911 | lodash.any = some;
|
15912 | lodash.contains = includes;
|
15913 | lodash.eq = isEqual;
|
15914 | lodash.detect = find;
|
15915 | lodash.foldl = reduce;
|
15916 | lodash.foldr = reduceRight;
|
15917 | lodash.head = first;
|
15918 | lodash.include = includes;
|
15919 | lodash.inject = reduce;
|
15920 |
|
15921 | mixin(lodash, (function() {
|
15922 | var source = {};
|
15923 | baseForOwn(lodash, function(func, methodName) {
|
15924 | if (!lodash.prototype[methodName]) {
|
15925 | source[methodName] = func;
|
15926 | }
|
15927 | });
|
15928 | return source;
|
15929 | }()), false);
|
15930 |
|
15931 | /*------------------------------------------------------------------------*/
|
15932 |
|
15933 | // Add functions capable of returning wrapped and unwrapped values when chaining.
|
15934 | lodash.sample = sample;
|
15935 |
|
15936 | lodash.prototype.sample = function(n) {
|
15937 | if (!this.__chain__ && n == null) {
|
15938 | return sample(this.value());
|
15939 | }
|
15940 | return this.thru(function(value) {
|
15941 | return sample(value, n);
|
15942 | });
|
15943 | };
|
15944 |
|
15945 | /*------------------------------------------------------------------------*/
|
15946 |
|
15947 | /**
|
15948 | * The semantic version number.
|
15949 | *
|
15950 | * @static
|
15951 | * @memberOf _
|
15952 | * @type string
|
15953 | */
|
15954 | lodash.VERSION = VERSION;
|
15955 |
|
15956 | // Assign default placeholders.
|
15957 | arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
|
15958 | lodash[methodName].placeholder = lodash;
|
15959 | });
|
15960 |
|
15961 | // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
|
15962 | arrayEach(['drop', 'take'], function(methodName, index) {
|
15963 | LazyWrapper.prototype[methodName] = function(n) {
|
15964 | var filtered = this.__filtered__;
|
15965 | if (filtered && !index) {
|
15966 | return new LazyWrapper(this);
|
15967 | }
|
15968 | n = n == null ? 1 : nativeMax(nativeFloor(n) || 0, 0);
|
15969 |
|
15970 | var result = this.clone();
|
15971 | if (filtered) {
|
15972 | result.__takeCount__ = nativeMin(result.__takeCount__, n);
|
15973 | } else {
|
15974 | result.__views__.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') });
|
15975 | }
|
15976 | return result;
|
15977 | };
|
15978 |
|
15979 | LazyWrapper.prototype[methodName + 'Right'] = function(n) {
|
15980 | return this.reverse()[methodName](n).reverse();
|
15981 | };
|
15982 | });
|
15983 |
|
15984 | // Add `LazyWrapper` methods that accept an `iteratee` value.
|
15985 | arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
|
15986 | var type = index + 1,
|
15987 | isFilter = type != LAZY_MAP_FLAG;
|
15988 |
|
15989 | LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
|
15990 | var result = this.clone();
|
15991 | result.__iteratees__.push({ 'iteratee': getCallback(iteratee, thisArg, 1), 'type': type });
|
15992 | result.__filtered__ = result.__filtered__ || isFilter;
|
15993 | return result;
|
15994 | };
|
15995 | });
|
15996 |
|
15997 | // Add `LazyWrapper` methods for `_.first` and `_.last`.
|
15998 | arrayEach(['first', 'last'], function(methodName, index) {
|
15999 | var takeName = 'take' + (index ? 'Right' : '');
|
16000 |
|
16001 | LazyWrapper.prototype[methodName] = function() {
|
16002 | return this[takeName](1).value()[0];
|
16003 | };
|
16004 | });
|
16005 |
|
16006 | // Add `LazyWrapper` methods for `_.initial` and `_.rest`.
|
16007 | arrayEach(['initial', 'rest'], function(methodName, index) {
|
16008 | var dropName = 'drop' + (index ? '' : 'Right');
|
16009 |
|
16010 | LazyWrapper.prototype[methodName] = function() {
|
16011 | return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
|
16012 | };
|
16013 | });
|
16014 |
|
16015 | // Add `LazyWrapper` methods for `_.pluck` and `_.where`.
|
16016 | arrayEach(['pluck', 'where'], function(methodName, index) {
|
16017 | var operationName = index ? 'filter' : 'map',
|
16018 | createCallback = index ? baseMatches : property;
|
16019 |
|
16020 | LazyWrapper.prototype[methodName] = function(value) {
|
16021 | return this[operationName](createCallback(value));
|
16022 | };
|
16023 | });
|
16024 |
|
16025 | LazyWrapper.prototype.compact = function() {
|
16026 | return this.filter(identity);
|
16027 | };
|
16028 |
|
16029 | LazyWrapper.prototype.reject = function(predicate, thisArg) {
|
16030 | predicate = getCallback(predicate, thisArg, 1);
|
16031 | return this.filter(function(value) {
|
16032 | return !predicate(value);
|
16033 | });
|
16034 | };
|
16035 |
|
16036 | LazyWrapper.prototype.slice = function(start, end) {
|
16037 | start = start == null ? 0 : (+start || 0);
|
16038 |
|
16039 | var result = this;
|
16040 | if (result.__filtered__ && (start > 0 || end < 0)) {
|
16041 | return new LazyWrapper(result);
|
16042 | }
|
16043 | if (start < 0) {
|
16044 | result = result.takeRight(-start);
|
16045 | } else if (start) {
|
16046 | result = result.drop(start);
|
16047 | }
|
16048 | if (end !== undefined) {
|
16049 | end = (+end || 0);
|
16050 | result = end < 0 ? result.dropRight(-end) : result.take(end - start);
|
16051 | }
|
16052 | return result;
|
16053 | };
|
16054 |
|
16055 | LazyWrapper.prototype.takeRightWhile = function(predicate, thisArg) {
|
16056 | return this.reverse().takeWhile(predicate, thisArg).reverse();
|
16057 | };
|
16058 |
|
16059 | LazyWrapper.prototype.toArray = function() {
|
16060 | return this.take(POSITIVE_INFINITY);
|
16061 | };
|
16062 |
|
16063 | // Add `LazyWrapper` methods to `lodash.prototype`.
|
16064 | baseForOwn(LazyWrapper.prototype, function(func, methodName) {
|
16065 | var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName),
|
16066 | retUnwrapped = /^(?:first|last)$/.test(methodName),
|
16067 | lodashFunc = lodash[retUnwrapped ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName];
|
16068 |
|
16069 | if (!lodashFunc) {
|
16070 | return;
|
16071 | }
|
16072 | lodash.prototype[methodName] = function() {
|
16073 | var args = retUnwrapped ? [1] : arguments,
|
16074 | chainAll = this.__chain__,
|
16075 | value = this.__wrapped__,
|
16076 | isHybrid = !!this.__actions__.length,
|
16077 | isLazy = value instanceof LazyWrapper,
|
16078 | iteratee = args[0],
|
16079 | useLazy = isLazy || isArray(value);
|
16080 |
|
16081 | if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
|
16082 | // Avoid lazy use if the iteratee has a "length" value other than `1`.
|
16083 | isLazy = useLazy = false;
|
16084 | }
|
16085 | var interceptor = function(value) {
|
16086 | return (retUnwrapped && chainAll)
|
16087 | ? lodashFunc(value, 1)[0]
|
16088 | : lodashFunc.apply(undefined, arrayPush([value], args));
|
16089 | };
|
16090 |
|
16091 | var action = { 'func': thru, 'args': [interceptor], 'thisArg': undefined },
|
16092 | onlyLazy = isLazy && !isHybrid;
|
16093 |
|
16094 | if (retUnwrapped && !chainAll) {
|
16095 | if (onlyLazy) {
|
16096 | value = value.clone();
|
16097 | value.__actions__.push(action);
|
16098 | return func.call(value);
|
16099 | }
|
16100 | return lodashFunc.call(undefined, this.value())[0];
|
16101 | }
|
16102 | if (!retUnwrapped && useLazy) {
|
16103 | value = onlyLazy ? value : new LazyWrapper(this);
|
16104 | var result = func.apply(value, args);
|
16105 | result.__actions__.push(action);
|
16106 | return new LodashWrapper(result, chainAll);
|
16107 | }
|
16108 | return this.thru(interceptor);
|
16109 | };
|
16110 | });
|
16111 |
|
16112 | // Add `Array` and `String` methods to `lodash.prototype`.
|
16113 | arrayEach(['join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) {
|
16114 | var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName],
|
16115 | chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
|
16116 | retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
|
16117 |
|
16118 | lodash.prototype[methodName] = function() {
|
16119 | var args = arguments;
|
16120 | if (retUnwrapped && !this.__chain__) {
|
16121 | return func.apply(this.value(), args);
|
16122 | }
|
16123 | return this[chainName](function(value) {
|
16124 | return func.apply(value, args);
|
16125 | });
|
16126 | };
|
16127 | });
|
16128 |
|
16129 | // Map minified function names to their real names.
|
16130 | baseForOwn(LazyWrapper.prototype, function(func, methodName) {
|
16131 | var lodashFunc = lodash[methodName];
|
16132 | if (lodashFunc) {
|
16133 | var key = lodashFunc.name,
|
16134 | names = realNames[key] || (realNames[key] = []);
|
16135 |
|
16136 | names.push({ 'name': methodName, 'func': lodashFunc });
|
16137 | }
|
16138 | });
|
16139 |
|
16140 | realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }];
|
16141 |
|
16142 | // Add functions to the lazy wrapper.
|
16143 | LazyWrapper.prototype.clone = lazyClone;
|
16144 | LazyWrapper.prototype.reverse = lazyReverse;
|
16145 | LazyWrapper.prototype.value = lazyValue;
|
16146 |
|
16147 | // Add chaining functions to the `lodash` wrapper.
|
16148 | lodash.prototype.chain = wrapperChain;
|
16149 | lodash.prototype.commit = wrapperCommit;
|
16150 | lodash.prototype.concat = wrapperConcat;
|
16151 | lodash.prototype.plant = wrapperPlant;
|
16152 | lodash.prototype.reverse = wrapperReverse;
|
16153 | lodash.prototype.toString = wrapperToString;
|
16154 | lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
|
16155 |
|
16156 | // Add function aliases to the `lodash` wrapper.
|
16157 | lodash.prototype.collect = lodash.prototype.map;
|
16158 | lodash.prototype.head = lodash.prototype.first;
|
16159 | lodash.prototype.select = lodash.prototype.filter;
|
16160 | lodash.prototype.tail = lodash.prototype.rest;
|
16161 |
|
16162 | return lodash;
|
16163 | }
|
16164 |
|
16165 | /*--------------------------------------------------------------------------*/
|
16166 |
|
16167 | // Export lodash.
|
16168 | var _ = runInContext();
|
16169 |
|
16170 | // Some AMD build optimizers like r.js check for condition patterns like the following:
|
16171 | if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
|
16172 | // Expose lodash to the global object when an AMD loader is present to avoid
|
16173 | // errors in cases where lodash is loaded by a script tag and not intended
|
16174 | // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
|
16175 | // more details.
|
16176 | root._ = _;
|
16177 |
|
16178 | // Define as an anonymous module so, through path mapping, it can be
|
16179 | // referenced as the "underscore" module.
|
16180 | define(function() {
|
16181 | return _;
|
16182 | });
|
16183 | }
|
16184 | // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
|
16185 | else if (freeExports && freeModule) {
|
16186 | // Export for Node.js or RingoJS.
|
16187 | if (moduleExports) {
|
16188 | (freeModule.exports = _)._ = _;
|
16189 | }
|
16190 | // Export for Rhino with CommonJS support.
|
16191 | else {
|
16192 | freeExports._ = _;
|
16193 | }
|
16194 | }
|
16195 | else {
|
16196 | // Export for a browser or Rhino.
|
16197 | root._ = _;
|
16198 | }
|
16199 | }.call(this));
|
16200 |
|
16201 | }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
|
16202 | },{}],11:[function(require,module,exports){
|
16203 | // Top level file is just a mixin of submodules & constants
|
16204 | 'use strict';
|
16205 |
|
16206 | var assign = require('./lib/utils/common').assign;
|
16207 |
|
16208 | var deflate = require('./lib/deflate');
|
16209 | var inflate = require('./lib/inflate');
|
16210 | var constants = require('./lib/zlib/constants');
|
16211 |
|
16212 | var pako = {};
|
16213 |
|
16214 | assign(pako, deflate, inflate, constants);
|
16215 |
|
16216 | module.exports = pako;
|
16217 |
|
16218 | },{"./lib/deflate":12,"./lib/inflate":13,"./lib/utils/common":14,"./lib/zlib/constants":17}],12:[function(require,module,exports){
|
16219 | 'use strict';
|
16220 |
|
16221 |
|
16222 | var zlib_deflate = require('./zlib/deflate.js');
|
16223 | var utils = require('./utils/common');
|
16224 | var strings = require('./utils/strings');
|
16225 | var msg = require('./zlib/messages');
|
16226 | var zstream = require('./zlib/zstream');
|
16227 |
|
16228 | var toString = Object.prototype.toString;
|
16229 |
|
16230 | /* Public constants ==========================================================*/
|
16231 | /* ===========================================================================*/
|
16232 |
|
16233 | var Z_NO_FLUSH = 0;
|
16234 | var Z_FINISH = 4;
|
16235 |
|
16236 | var Z_OK = 0;
|
16237 | var Z_STREAM_END = 1;
|
16238 | var Z_SYNC_FLUSH = 2;
|
16239 |
|
16240 | var Z_DEFAULT_COMPRESSION = -1;
|
16241 |
|
16242 | var Z_DEFAULT_STRATEGY = 0;
|
16243 |
|
16244 | var Z_DEFLATED = 8;
|
16245 |
|
16246 | /* ===========================================================================*/
|
16247 |
|
16248 |
|
16249 | /**
|
16250 | * class Deflate
|
16251 | *
|
16252 | * Generic JS-style wrapper for zlib calls. If you don't need
|
16253 | * streaming behaviour - use more simple functions: [[deflate]],
|
16254 | * [[deflateRaw]] and [[gzip]].
|
16255 | **/
|
16256 |
|
16257 | /* internal
|
16258 | * Deflate.chunks -> Array
|
16259 | *
|
16260 | * Chunks of output data, if [[Deflate#onData]] not overriden.
|
16261 | **/
|
16262 |
|
16263 | /**
|
16264 | * Deflate.result -> Uint8Array|Array
|
16265 | *
|
16266 | * Compressed result, generated by default [[Deflate#onData]]
|
16267 | * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
|
16268 | * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
|
16269 | * push a chunk with explicit flush (call [[Deflate#push]] with
|
16270 | * `Z_SYNC_FLUSH` param).
|
16271 | **/
|
16272 |
|
16273 | /**
|
16274 | * Deflate.err -> Number
|
16275 | *
|
16276 | * Error code after deflate finished. 0 (Z_OK) on success.
|
16277 | * You will not need it in real life, because deflate errors
|
16278 | * are possible only on wrong options or bad `onData` / `onEnd`
|
16279 | * custom handlers.
|
16280 | **/
|
16281 |
|
16282 | /**
|
16283 | * Deflate.msg -> String
|
16284 | *
|
16285 | * Error message, if [[Deflate.err]] != 0
|
16286 | **/
|
16287 |
|
16288 |
|
16289 | /**
|
16290 | * new Deflate(options)
|
16291 | * - options (Object): zlib deflate options.
|
16292 | *
|
16293 | * Creates new deflator instance with specified params. Throws exception
|
16294 | * on bad params. Supported options:
|
16295 | *
|
16296 | * - `level`
|
16297 | * - `windowBits`
|
16298 | * - `memLevel`
|
16299 | * - `strategy`
|
16300 | *
|
16301 | * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
|
16302 | * for more information on these.
|
16303 | *
|
16304 | * Additional options, for internal needs:
|
16305 | *
|
16306 | * - `chunkSize` - size of generated data chunks (16K by default)
|
16307 | * - `raw` (Boolean) - do raw deflate
|
16308 | * - `gzip` (Boolean) - create gzip wrapper
|
16309 | * - `to` (String) - if equal to 'string', then result will be "binary string"
|
16310 | * (each char code [0..255])
|
16311 | * - `header` (Object) - custom header for gzip
|
16312 | * - `text` (Boolean) - true if compressed data believed to be text
|
16313 | * - `time` (Number) - modification time, unix timestamp
|
16314 | * - `os` (Number) - operation system code
|
16315 | * - `extra` (Array) - array of bytes with extra data (max 65536)
|
16316 | * - `name` (String) - file name (binary string)
|
16317 | * - `comment` (String) - comment (binary string)
|
16318 | * - `hcrc` (Boolean) - true if header crc should be added
|
16319 | *
|
16320 | * ##### Example:
|
16321 | *
|
16322 | * ```javascript
|
16323 | * var pako = require('pako')
|
16324 | * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
|
16325 | * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
|
16326 | *
|
16327 | * var deflate = new pako.Deflate({ level: 3});
|
16328 | *
|
16329 | * deflate.push(chunk1, false);
|
16330 | * deflate.push(chunk2, true); // true -> last chunk
|
16331 | *
|
16332 | * if (deflate.err) { throw new Error(deflate.err); }
|
16333 | *
|
16334 | * console.log(deflate.result);
|
16335 | * ```
|
16336 | **/
|
16337 | var Deflate = function(options) {
|
16338 |
|
16339 | this.options = utils.assign({
|
16340 | level: Z_DEFAULT_COMPRESSION,
|
16341 | method: Z_DEFLATED,
|
16342 | chunkSize: 16384,
|
16343 | windowBits: 15,
|
16344 | memLevel: 8,
|
16345 | strategy: Z_DEFAULT_STRATEGY,
|
16346 | to: ''
|
16347 | }, options || {});
|
16348 |
|
16349 | var opt = this.options;
|
16350 |
|
16351 | if (opt.raw && (opt.windowBits > 0)) {
|
16352 | opt.windowBits = -opt.windowBits;
|
16353 | }
|
16354 |
|
16355 | else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
|
16356 | opt.windowBits += 16;
|
16357 | }
|
16358 |
|
16359 | this.err = 0; // error code, if happens (0 = Z_OK)
|
16360 | this.msg = ''; // error message
|
16361 | this.ended = false; // used to avoid multiple onEnd() calls
|
16362 | this.chunks = []; // chunks of compressed data
|
16363 |
|
16364 | this.strm = new zstream();
|
16365 | this.strm.avail_out = 0;
|
16366 |
|
16367 | var status = zlib_deflate.deflateInit2(
|
16368 | this.strm,
|
16369 | opt.level,
|
16370 | opt.method,
|
16371 | opt.windowBits,
|
16372 | opt.memLevel,
|
16373 | opt.strategy
|
16374 | );
|
16375 |
|
16376 | if (status !== Z_OK) {
|
16377 | throw new Error(msg[status]);
|
16378 | }
|
16379 |
|
16380 | if (opt.header) {
|
16381 | zlib_deflate.deflateSetHeader(this.strm, opt.header);
|
16382 | }
|
16383 | };
|
16384 |
|
16385 | /**
|
16386 | * Deflate#push(data[, mode]) -> Boolean
|
16387 | * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
|
16388 | * converted to utf8 byte sequence.
|
16389 | * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
|
16390 | * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
|
16391 | *
|
16392 | * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
|
16393 | * new compressed chunks. Returns `true` on success. The last data block must have
|
16394 | * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
|
16395 | * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
|
16396 | * can use mode Z_SYNC_FLUSH, keeping the compression context.
|
16397 | *
|
16398 | * On fail call [[Deflate#onEnd]] with error code and return false.
|
16399 | *
|
16400 | * We strongly recommend to use `Uint8Array` on input for best speed (output
|
16401 | * array format is detected automatically). Also, don't skip last param and always
|
16402 | * use the same type in your code (boolean or number). That will improve JS speed.
|
16403 | *
|
16404 | * For regular `Array`-s make sure all elements are [0..255].
|
16405 | *
|
16406 | * ##### Example
|
16407 | *
|
16408 | * ```javascript
|
16409 | * push(chunk, false); // push one of data chunks
|
16410 | * ...
|
16411 | * push(chunk, true); // push last chunk
|
16412 | * ```
|
16413 | **/
|
16414 | Deflate.prototype.push = function(data, mode) {
|
16415 | var strm = this.strm;
|
16416 | var chunkSize = this.options.chunkSize;
|
16417 | var status, _mode;
|
16418 |
|
16419 | if (this.ended) { return false; }
|
16420 |
|
16421 | _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
|
16422 |
|
16423 | // Convert data if needed
|
16424 | if (typeof data === 'string') {
|
16425 | // If we need to compress text, change encoding to utf8.
|
16426 | strm.input = strings.string2buf(data);
|
16427 | } else if (toString.call(data) === '[object ArrayBuffer]') {
|
16428 | strm.input = new Uint8Array(data);
|
16429 | } else {
|
16430 | strm.input = data;
|
16431 | }
|
16432 |
|
16433 | strm.next_in = 0;
|
16434 | strm.avail_in = strm.input.length;
|
16435 |
|
16436 | do {
|
16437 | if (strm.avail_out === 0) {
|
16438 | strm.output = new utils.Buf8(chunkSize);
|
16439 | strm.next_out = 0;
|
16440 | strm.avail_out = chunkSize;
|
16441 | }
|
16442 | status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
|
16443 |
|
16444 | if (status !== Z_STREAM_END && status !== Z_OK) {
|
16445 | this.onEnd(status);
|
16446 | this.ended = true;
|
16447 | return false;
|
16448 | }
|
16449 | if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
|
16450 | if (this.options.to === 'string') {
|
16451 | this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
|
16452 | } else {
|
16453 | this.onData(utils.shrinkBuf(strm.output, strm.next_out));
|
16454 | }
|
16455 | }
|
16456 | } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
|
16457 |
|
16458 | // Finalize on the last chunk.
|
16459 | if (_mode === Z_FINISH) {
|
16460 | status = zlib_deflate.deflateEnd(this.strm);
|
16461 | this.onEnd(status);
|
16462 | this.ended = true;
|
16463 | return status === Z_OK;
|
16464 | }
|
16465 |
|
16466 | // callback interim results if Z_SYNC_FLUSH.
|
16467 | if (_mode === Z_SYNC_FLUSH) {
|
16468 | this.onEnd(Z_OK);
|
16469 | strm.avail_out = 0;
|
16470 | return true;
|
16471 | }
|
16472 |
|
16473 | return true;
|
16474 | };
|
16475 |
|
16476 |
|
16477 | /**
|
16478 | * Deflate#onData(chunk) -> Void
|
16479 | * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
|
16480 | * on js engine support. When string output requested, each chunk
|
16481 | * will be string.
|
16482 | *
|
16483 | * By default, stores data blocks in `chunks[]` property and glue
|
16484 | * those in `onEnd`. Override this handler, if you need another behaviour.
|
16485 | **/
|
16486 | Deflate.prototype.onData = function(chunk) {
|
16487 | this.chunks.push(chunk);
|
16488 | };
|
16489 |
|
16490 |
|
16491 | /**
|
16492 | * Deflate#onEnd(status) -> Void
|
16493 | * - status (Number): deflate status. 0 (Z_OK) on success,
|
16494 | * other if not.
|
16495 | *
|
16496 | * Called once after you tell deflate that the input stream is
|
16497 | * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
|
16498 | * or if an error happened. By default - join collected chunks,
|
16499 | * free memory and fill `results` / `err` properties.
|
16500 | **/
|
16501 | Deflate.prototype.onEnd = function(status) {
|
16502 | // On success - join
|
16503 | if (status === Z_OK) {
|
16504 | if (this.options.to === 'string') {
|
16505 | this.result = this.chunks.join('');
|
16506 | } else {
|
16507 | this.result = utils.flattenChunks(this.chunks);
|
16508 | }
|
16509 | }
|
16510 | this.chunks = [];
|
16511 | this.err = status;
|
16512 | this.msg = this.strm.msg;
|
16513 | };
|
16514 |
|
16515 |
|
16516 | /**
|
16517 | * deflate(data[, options]) -> Uint8Array|Array|String
|
16518 | * - data (Uint8Array|Array|String): input data to compress.
|
16519 | * - options (Object): zlib deflate options.
|
16520 | *
|
16521 | * Compress `data` with deflate alrorythm and `options`.
|
16522 | *
|
16523 | * Supported options are:
|
16524 | *
|
16525 | * - level
|
16526 | * - windowBits
|
16527 | * - memLevel
|
16528 | * - strategy
|
16529 | *
|
16530 | * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
|
16531 | * for more information on these.
|
16532 | *
|
16533 | * Sugar (options):
|
16534 | *
|
16535 | * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
|
16536 | * negative windowBits implicitly.
|
16537 | * - `to` (String) - if equal to 'string', then result will be "binary string"
|
16538 | * (each char code [0..255])
|
16539 | *
|
16540 | * ##### Example:
|
16541 | *
|
16542 | * ```javascript
|
16543 | * var pako = require('pako')
|
16544 | * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
|
16545 | *
|
16546 | * console.log(pako.deflate(data));
|
16547 | * ```
|
16548 | **/
|
16549 | function deflate(input, options) {
|
16550 | var deflator = new Deflate(options);
|
16551 |
|
16552 | deflator.push(input, true);
|
16553 |
|
16554 | // That will never happens, if you don't cheat with options :)
|
16555 | if (deflator.err) { throw deflator.msg; }
|
16556 |
|
16557 | return deflator.result;
|
16558 | }
|
16559 |
|
16560 |
|
16561 | /**
|
16562 | * deflateRaw(data[, options]) -> Uint8Array|Array|String
|
16563 | * - data (Uint8Array|Array|String): input data to compress.
|
16564 | * - options (Object): zlib deflate options.
|
16565 | *
|
16566 | * The same as [[deflate]], but creates raw data, without wrapper
|
16567 | * (header and adler32 crc).
|
16568 | **/
|
16569 | function deflateRaw(input, options) {
|
16570 | options = options || {};
|
16571 | options.raw = true;
|
16572 | return deflate(input, options);
|
16573 | }
|
16574 |
|
16575 |
|
16576 | /**
|
16577 | * gzip(data[, options]) -> Uint8Array|Array|String
|
16578 | * - data (Uint8Array|Array|String): input data to compress.
|
16579 | * - options (Object): zlib deflate options.
|
16580 | *
|
16581 | * The same as [[deflate]], but create gzip wrapper instead of
|
16582 | * deflate one.
|
16583 | **/
|
16584 | function gzip(input, options) {
|
16585 | options = options || {};
|
16586 | options.gzip = true;
|
16587 | return deflate(input, options);
|
16588 | }
|
16589 |
|
16590 |
|
16591 | exports.Deflate = Deflate;
|
16592 | exports.deflate = deflate;
|
16593 | exports.deflateRaw = deflateRaw;
|
16594 | exports.gzip = gzip;
|
16595 |
|
16596 | },{"./utils/common":14,"./utils/strings":15,"./zlib/deflate.js":19,"./zlib/messages":24,"./zlib/zstream":26}],13:[function(require,module,exports){
|
16597 | 'use strict';
|
16598 |
|
16599 |
|
16600 | var zlib_inflate = require('./zlib/inflate.js');
|
16601 | var utils = require('./utils/common');
|
16602 | var strings = require('./utils/strings');
|
16603 | var c = require('./zlib/constants');
|
16604 | var msg = require('./zlib/messages');
|
16605 | var zstream = require('./zlib/zstream');
|
16606 | var gzheader = require('./zlib/gzheader');
|
16607 |
|
16608 | var toString = Object.prototype.toString;
|
16609 |
|
16610 | /**
|
16611 | * class Inflate
|
16612 | *
|
16613 | * Generic JS-style wrapper for zlib calls. If you don't need
|
16614 | * streaming behaviour - use more simple functions: [[inflate]]
|
16615 | * and [[inflateRaw]].
|
16616 | **/
|
16617 |
|
16618 | /* internal
|
16619 | * inflate.chunks -> Array
|
16620 | *
|
16621 | * Chunks of output data, if [[Inflate#onData]] not overriden.
|
16622 | **/
|
16623 |
|
16624 | /**
|
16625 | * Inflate.result -> Uint8Array|Array|String
|
16626 | *
|
16627 | * Uncompressed result, generated by default [[Inflate#onData]]
|
16628 | * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
|
16629 | * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
|
16630 | * push a chunk with explicit flush (call [[Inflate#push]] with
|
16631 | * `Z_SYNC_FLUSH` param).
|
16632 | **/
|
16633 |
|
16634 | /**
|
16635 | * Inflate.err -> Number
|
16636 | *
|
16637 | * Error code after inflate finished. 0 (Z_OK) on success.
|
16638 | * Should be checked if broken data possible.
|
16639 | **/
|
16640 |
|
16641 | /**
|
16642 | * Inflate.msg -> String
|
16643 | *
|
16644 | * Error message, if [[Inflate.err]] != 0
|
16645 | **/
|
16646 |
|
16647 |
|
16648 | /**
|
16649 | * new Inflate(options)
|
16650 | * - options (Object): zlib inflate options.
|
16651 | *
|
16652 | * Creates new inflator instance with specified params. Throws exception
|
16653 | * on bad params. Supported options:
|
16654 | *
|
16655 | * - `windowBits`
|
16656 | *
|
16657 | * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
|
16658 | * for more information on these.
|
16659 | *
|
16660 | * Additional options, for internal needs:
|
16661 | *
|
16662 | * - `chunkSize` - size of generated data chunks (16K by default)
|
16663 | * - `raw` (Boolean) - do raw inflate
|
16664 | * - `to` (String) - if equal to 'string', then result will be converted
|
16665 | * from utf8 to utf16 (javascript) string. When string output requested,
|
16666 | * chunk length can differ from `chunkSize`, depending on content.
|
16667 | *
|
16668 | * By default, when no options set, autodetect deflate/gzip data format via
|
16669 | * wrapper header.
|
16670 | *
|
16671 | * ##### Example:
|
16672 | *
|
16673 | * ```javascript
|
16674 | * var pako = require('pako')
|
16675 | * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
|
16676 | * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
|
16677 | *
|
16678 | * var inflate = new pako.Inflate({ level: 3});
|
16679 | *
|
16680 | * inflate.push(chunk1, false);
|
16681 | * inflate.push(chunk2, true); // true -> last chunk
|
16682 | *
|
16683 | * if (inflate.err) { throw new Error(inflate.err); }
|
16684 | *
|
16685 | * console.log(inflate.result);
|
16686 | * ```
|
16687 | **/
|
16688 | var Inflate = function(options) {
|
16689 |
|
16690 | this.options = utils.assign({
|
16691 | chunkSize: 16384,
|
16692 | windowBits: 0,
|
16693 | to: ''
|
16694 | }, options || {});
|
16695 |
|
16696 | var opt = this.options;
|
16697 |
|
16698 | // Force window size for `raw` data, if not set directly,
|
16699 | // because we have no header for autodetect.
|
16700 | if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
|
16701 | opt.windowBits = -opt.windowBits;
|
16702 | if (opt.windowBits === 0) { opt.windowBits = -15; }
|
16703 | }
|
16704 |
|
16705 | // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
|
16706 | if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
|
16707 | !(options && options.windowBits)) {
|
16708 | opt.windowBits += 32;
|
16709 | }
|
16710 |
|
16711 | // Gzip header has no info about windows size, we can do autodetect only
|
16712 | // for deflate. So, if window size not set, force it to max when gzip possible
|
16713 | if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
|
16714 | // bit 3 (16) -> gzipped data
|
16715 | // bit 4 (32) -> autodetect gzip/deflate
|
16716 | if ((opt.windowBits & 15) === 0) {
|
16717 | opt.windowBits |= 15;
|
16718 | }
|
16719 | }
|
16720 |
|
16721 | this.err = 0; // error code, if happens (0 = Z_OK)
|
16722 | this.msg = ''; // error message
|
16723 | this.ended = false; // used to avoid multiple onEnd() calls
|
16724 | this.chunks = []; // chunks of compressed data
|
16725 |
|
16726 | this.strm = new zstream();
|
16727 | this.strm.avail_out = 0;
|
16728 |
|
16729 | var status = zlib_inflate.inflateInit2(
|
16730 | this.strm,
|
16731 | opt.windowBits
|
16732 | );
|
16733 |
|
16734 | if (status !== c.Z_OK) {
|
16735 | throw new Error(msg[status]);
|
16736 | }
|
16737 |
|
16738 | this.header = new gzheader();
|
16739 |
|
16740 | zlib_inflate.inflateGetHeader(this.strm, this.header);
|
16741 | };
|
16742 |
|
16743 | /**
|
16744 | * Inflate#push(data[, mode]) -> Boolean
|
16745 | * - data (Uint8Array|Array|ArrayBuffer|String): input data
|
16746 | * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
|
16747 | * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
|
16748 | *
|
16749 | * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
|
16750 | * new output chunks. Returns `true` on success. The last data block must have
|
16751 | * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
|
16752 | * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
|
16753 | * can use mode Z_SYNC_FLUSH, keeping the decompression context.
|
16754 | *
|
16755 | * On fail call [[Inflate#onEnd]] with error code and return false.
|
16756 | *
|
16757 | * We strongly recommend to use `Uint8Array` on input for best speed (output
|
16758 | * format is detected automatically). Also, don't skip last param and always
|
16759 | * use the same type in your code (boolean or number). That will improve JS speed.
|
16760 | *
|
16761 | * For regular `Array`-s make sure all elements are [0..255].
|
16762 | *
|
16763 | * ##### Example
|
16764 | *
|
16765 | * ```javascript
|
16766 | * push(chunk, false); // push one of data chunks
|
16767 | * ...
|
16768 | * push(chunk, true); // push last chunk
|
16769 | * ```
|
16770 | **/
|
16771 | Inflate.prototype.push = function(data, mode) {
|
16772 | var strm = this.strm;
|
16773 | var chunkSize = this.options.chunkSize;
|
16774 | var status, _mode;
|
16775 | var next_out_utf8, tail, utf8str;
|
16776 |
|
16777 | if (this.ended) { return false; }
|
16778 | _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
|
16779 |
|
16780 | // Convert data if needed
|
16781 | if (typeof data === 'string') {
|
16782 | // Only binary strings can be decompressed on practice
|
16783 | strm.input = strings.binstring2buf(data);
|
16784 | } else if (toString.call(data) === '[object ArrayBuffer]') {
|
16785 | strm.input = new Uint8Array(data);
|
16786 | } else {
|
16787 | strm.input = data;
|
16788 | }
|
16789 |
|
16790 | strm.next_in = 0;
|
16791 | strm.avail_in = strm.input.length;
|
16792 |
|
16793 | do {
|
16794 | if (strm.avail_out === 0) {
|
16795 | strm.output = new utils.Buf8(chunkSize);
|
16796 | strm.next_out = 0;
|
16797 | strm.avail_out = chunkSize;
|
16798 | }
|
16799 |
|
16800 | status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
|
16801 |
|
16802 | if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
|
16803 | this.onEnd(status);
|
16804 | this.ended = true;
|
16805 | return false;
|
16806 | }
|
16807 |
|
16808 | if (strm.next_out) {
|
16809 | if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
|
16810 |
|
16811 | if (this.options.to === 'string') {
|
16812 |
|
16813 | next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
|
16814 |
|
16815 | tail = strm.next_out - next_out_utf8;
|
16816 | utf8str = strings.buf2string(strm.output, next_out_utf8);
|
16817 |
|
16818 | // move tail
|
16819 | strm.next_out = tail;
|
16820 | strm.avail_out = chunkSize - tail;
|
16821 | if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
|
16822 |
|
16823 | this.onData(utf8str);
|
16824 |
|
16825 | } else {
|
16826 | this.onData(utils.shrinkBuf(strm.output, strm.next_out));
|
16827 | }
|
16828 | }
|
16829 | }
|
16830 | } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
|
16831 |
|
16832 | if (status === c.Z_STREAM_END) {
|
16833 | _mode = c.Z_FINISH;
|
16834 | }
|
16835 |
|
16836 | // Finalize on the last chunk.
|
16837 | if (_mode === c.Z_FINISH) {
|
16838 | status = zlib_inflate.inflateEnd(this.strm);
|
16839 | this.onEnd(status);
|
16840 | this.ended = true;
|
16841 | return status === c.Z_OK;
|
16842 | }
|
16843 |
|
16844 | // callback interim results if Z_SYNC_FLUSH.
|
16845 | if (_mode === c.Z_SYNC_FLUSH) {
|
16846 | this.onEnd(c.Z_OK);
|
16847 | strm.avail_out = 0;
|
16848 | return true;
|
16849 | }
|
16850 |
|
16851 | return true;
|
16852 | };
|
16853 |
|
16854 |
|
16855 | /**
|
16856 | * Inflate#onData(chunk) -> Void
|
16857 | * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
|
16858 | * on js engine support. When string output requested, each chunk
|
16859 | * will be string.
|
16860 | *
|
16861 | * By default, stores data blocks in `chunks[]` property and glue
|
16862 | * those in `onEnd`. Override this handler, if you need another behaviour.
|
16863 | **/
|
16864 | Inflate.prototype.onData = function(chunk) {
|
16865 | this.chunks.push(chunk);
|
16866 | };
|
16867 |
|
16868 |
|
16869 | /**
|
16870 | * Inflate#onEnd(status) -> Void
|
16871 | * - status (Number): inflate status. 0 (Z_OK) on success,
|
16872 | * other if not.
|
16873 | *
|
16874 | * Called either after you tell inflate that the input stream is
|
16875 | * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
|
16876 | * or if an error happened. By default - join collected chunks,
|
16877 | * free memory and fill `results` / `err` properties.
|
16878 | **/
|
16879 | Inflate.prototype.onEnd = function(status) {
|
16880 | // On success - join
|
16881 | if (status === c.Z_OK) {
|
16882 | if (this.options.to === 'string') {
|
16883 | // Glue & convert here, until we teach pako to send
|
16884 | // utf8 alligned strings to onData
|
16885 | this.result = this.chunks.join('');
|
16886 | } else {
|
16887 | this.result = utils.flattenChunks(this.chunks);
|
16888 | }
|
16889 | }
|
16890 | this.chunks = [];
|
16891 | this.err = status;
|
16892 | this.msg = this.strm.msg;
|
16893 | };
|
16894 |
|
16895 |
|
16896 | /**
|
16897 | * inflate(data[, options]) -> Uint8Array|Array|String
|
16898 | * - data (Uint8Array|Array|String): input data to decompress.
|
16899 | * - options (Object): zlib inflate options.
|
16900 | *
|
16901 | * Decompress `data` with inflate/ungzip and `options`. Autodetect
|
16902 | * format via wrapper header by default. That's why we don't provide
|
16903 | * separate `ungzip` method.
|
16904 | *
|
16905 | * Supported options are:
|
16906 | *
|
16907 | * - windowBits
|
16908 | *
|
16909 | * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
|
16910 | * for more information.
|
16911 | *
|
16912 | * Sugar (options):
|
16913 | *
|
16914 | * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
|
16915 | * negative windowBits implicitly.
|
16916 | * - `to` (String) - if equal to 'string', then result will be converted
|
16917 | * from utf8 to utf16 (javascript) string. When string output requested,
|
16918 | * chunk length can differ from `chunkSize`, depending on content.
|
16919 | *
|
16920 | *
|
16921 | * ##### Example:
|
16922 | *
|
16923 | * ```javascript
|
16924 | * var pako = require('pako')
|
16925 | * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
|
16926 | * , output;
|
16927 | *
|
16928 | * try {
|
16929 | * output = pako.inflate(input);
|
16930 | * } catch (err)
|
16931 | * console.log(err);
|
16932 | * }
|
16933 | * ```
|
16934 | **/
|
16935 | function inflate(input, options) {
|
16936 | var inflator = new Inflate(options);
|
16937 |
|
16938 | inflator.push(input, true);
|
16939 |
|
16940 | // That will never happens, if you don't cheat with options :)
|
16941 | if (inflator.err) { throw inflator.msg; }
|
16942 |
|
16943 | return inflator.result;
|
16944 | }
|
16945 |
|
16946 |
|
16947 | /**
|
16948 | * inflateRaw(data[, options]) -> Uint8Array|Array|String
|
16949 | * - data (Uint8Array|Array|String): input data to decompress.
|
16950 | * - options (Object): zlib inflate options.
|
16951 | *
|
16952 | * The same as [[inflate]], but creates raw data, without wrapper
|
16953 | * (header and adler32 crc).
|
16954 | **/
|
16955 | function inflateRaw(input, options) {
|
16956 | options = options || {};
|
16957 | options.raw = true;
|
16958 | return inflate(input, options);
|
16959 | }
|
16960 |
|
16961 |
|
16962 | /**
|
16963 | * ungzip(data[, options]) -> Uint8Array|Array|String
|
16964 | * - data (Uint8Array|Array|String): input data to decompress.
|
16965 | * - options (Object): zlib inflate options.
|
16966 | *
|
16967 | * Just shortcut to [[inflate]], because it autodetects format
|
16968 | * by header.content. Done for convenience.
|
16969 | **/
|
16970 |
|
16971 |
|
16972 | exports.Inflate = Inflate;
|
16973 | exports.inflate = inflate;
|
16974 | exports.inflateRaw = inflateRaw;
|
16975 | exports.ungzip = inflate;
|
16976 |
|
16977 | },{"./utils/common":14,"./utils/strings":15,"./zlib/constants":17,"./zlib/gzheader":20,"./zlib/inflate.js":22,"./zlib/messages":24,"./zlib/zstream":26}],14:[function(require,module,exports){
|
16978 | 'use strict';
|
16979 |
|
16980 |
|
16981 | var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
|
16982 | (typeof Uint16Array !== 'undefined') &&
|
16983 | (typeof Int32Array !== 'undefined');
|
16984 |
|
16985 |
|
16986 | exports.assign = function (obj /*from1, from2, from3, ...*/) {
|
16987 | var sources = Array.prototype.slice.call(arguments, 1);
|
16988 | while (sources.length) {
|
16989 | var source = sources.shift();
|
16990 | if (!source) { continue; }
|
16991 |
|
16992 | if (typeof source !== 'object') {
|
16993 | throw new TypeError(source + 'must be non-object');
|
16994 | }
|
16995 |
|
16996 | for (var p in source) {
|
16997 | if (source.hasOwnProperty(p)) {
|
16998 | obj[p] = source[p];
|
16999 | }
|
17000 | }
|
17001 | }
|
17002 |
|
17003 | return obj;
|
17004 | };
|
17005 |
|
17006 |
|
17007 | // reduce buffer size, avoiding mem copy
|
17008 | exports.shrinkBuf = function (buf, size) {
|
17009 | if (buf.length === size) { return buf; }
|
17010 | if (buf.subarray) { return buf.subarray(0, size); }
|
17011 | buf.length = size;
|
17012 | return buf;
|
17013 | };
|
17014 |
|
17015 |
|
17016 | var fnTyped = {
|
17017 | arraySet: function (dest, src, src_offs, len, dest_offs) {
|
17018 | if (src.subarray && dest.subarray) {
|
17019 | dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
|
17020 | return;
|
17021 | }
|
17022 | // Fallback to ordinary array
|
17023 | for (var i=0; i<len; i++) {
|
17024 | dest[dest_offs + i] = src[src_offs + i];
|
17025 | }
|
17026 | },
|
17027 | // Join array of chunks to single array.
|
17028 | flattenChunks: function(chunks) {
|
17029 | var i, l, len, pos, chunk, result;
|
17030 |
|
17031 | // calculate data length
|
17032 | len = 0;
|
17033 | for (i=0, l=chunks.length; i<l; i++) {
|
17034 | len += chunks[i].length;
|
17035 | }
|
17036 |
|
17037 | // join chunks
|
17038 | result = new Uint8Array(len);
|
17039 | pos = 0;
|
17040 | for (i=0, l=chunks.length; i<l; i++) {
|
17041 | chunk = chunks[i];
|
17042 | result.set(chunk, pos);
|
17043 | pos += chunk.length;
|
17044 | }
|
17045 |
|
17046 | return result;
|
17047 | }
|
17048 | };
|
17049 |
|
17050 | var fnUntyped = {
|
17051 | arraySet: function (dest, src, src_offs, len, dest_offs) {
|
17052 | for (var i=0; i<len; i++) {
|
17053 | dest[dest_offs + i] = src[src_offs + i];
|
17054 | }
|
17055 | },
|
17056 | // Join array of chunks to single array.
|
17057 | flattenChunks: function(chunks) {
|
17058 | return [].concat.apply([], chunks);
|
17059 | }
|
17060 | };
|
17061 |
|
17062 |
|
17063 | // Enable/Disable typed arrays use, for testing
|
17064 | //
|
17065 | exports.setTyped = function (on) {
|
17066 | if (on) {
|
17067 | exports.Buf8 = Uint8Array;
|
17068 | exports.Buf16 = Uint16Array;
|
17069 | exports.Buf32 = Int32Array;
|
17070 | exports.assign(exports, fnTyped);
|
17071 | } else {
|
17072 | exports.Buf8 = Array;
|
17073 | exports.Buf16 = Array;
|
17074 | exports.Buf32 = Array;
|
17075 | exports.assign(exports, fnUntyped);
|
17076 | }
|
17077 | };
|
17078 |
|
17079 | exports.setTyped(TYPED_OK);
|
17080 |
|
17081 | },{}],15:[function(require,module,exports){
|
17082 | // String encode/decode helpers
|
17083 | 'use strict';
|
17084 |
|
17085 |
|
17086 | var utils = require('./common');
|
17087 |
|
17088 |
|
17089 | // Quick check if we can use fast array to bin string conversion
|
17090 | //
|
17091 | // - apply(Array) can fail on Android 2.2
|
17092 | // - apply(Uint8Array) can fail on iOS 5.1 Safary
|
17093 | //
|
17094 | var STR_APPLY_OK = true;
|
17095 | var STR_APPLY_UIA_OK = true;
|
17096 |
|
17097 | try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
|
17098 | try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
|
17099 |
|
17100 |
|
17101 | // Table with utf8 lengths (calculated by first byte of sequence)
|
17102 | // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
|
17103 | // because max possible codepoint is 0x10ffff
|
17104 | var _utf8len = new utils.Buf8(256);
|
17105 | for (var q=0; q<256; q++) {
|
17106 | _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
|
17107 | }
|
17108 | _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
|
17109 |
|
17110 |
|
17111 | // convert string to array (typed, when possible)
|
17112 | exports.string2buf = function (str) {
|
17113 | var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
|
17114 |
|
17115 | // count binary size
|
17116 | for (m_pos = 0; m_pos < str_len; m_pos++) {
|
17117 | c = str.charCodeAt(m_pos);
|
17118 | if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
|
17119 | c2 = str.charCodeAt(m_pos+1);
|
17120 | if ((c2 & 0xfc00) === 0xdc00) {
|
17121 | c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
|
17122 | m_pos++;
|
17123 | }
|
17124 | }
|
17125 | buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
|
17126 | }
|
17127 |
|
17128 | // allocate buffer
|
17129 | buf = new utils.Buf8(buf_len);
|
17130 |
|
17131 | // convert
|
17132 | for (i=0, m_pos = 0; i < buf_len; m_pos++) {
|
17133 | c = str.charCodeAt(m_pos);
|
17134 | if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
|
17135 | c2 = str.charCodeAt(m_pos+1);
|
17136 | if ((c2 & 0xfc00) === 0xdc00) {
|
17137 | c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
|
17138 | m_pos++;
|
17139 | }
|
17140 | }
|
17141 | if (c < 0x80) {
|
17142 | /* one byte */
|
17143 | buf[i++] = c;
|
17144 | } else if (c < 0x800) {
|
17145 | /* two bytes */
|
17146 | buf[i++] = 0xC0 | (c >>> 6);
|
17147 | buf[i++] = 0x80 | (c & 0x3f);
|
17148 | } else if (c < 0x10000) {
|
17149 | /* three bytes */
|
17150 | buf[i++] = 0xE0 | (c >>> 12);
|
17151 | buf[i++] = 0x80 | (c >>> 6 & 0x3f);
|
17152 | buf[i++] = 0x80 | (c & 0x3f);
|
17153 | } else {
|
17154 | /* four bytes */
|
17155 | buf[i++] = 0xf0 | (c >>> 18);
|
17156 | buf[i++] = 0x80 | (c >>> 12 & 0x3f);
|
17157 | buf[i++] = 0x80 | (c >>> 6 & 0x3f);
|
17158 | buf[i++] = 0x80 | (c & 0x3f);
|
17159 | }
|
17160 | }
|
17161 |
|
17162 | return buf;
|
17163 | };
|
17164 |
|
17165 | // Helper (used in 2 places)
|
17166 | function buf2binstring(buf, len) {
|
17167 | // use fallback for big arrays to avoid stack overflow
|
17168 | if (len < 65537) {
|
17169 | if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
|
17170 | return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
|
17171 | }
|
17172 | }
|
17173 |
|
17174 | var result = '';
|
17175 | for (var i=0; i < len; i++) {
|
17176 | result += String.fromCharCode(buf[i]);
|
17177 | }
|
17178 | return result;
|
17179 | }
|
17180 |
|
17181 |
|
17182 | // Convert byte array to binary string
|
17183 | exports.buf2binstring = function(buf) {
|
17184 | return buf2binstring(buf, buf.length);
|
17185 | };
|
17186 |
|
17187 |
|
17188 | // Convert binary string (typed, when possible)
|
17189 | exports.binstring2buf = function(str) {
|
17190 | var buf = new utils.Buf8(str.length);
|
17191 | for (var i=0, len=buf.length; i < len; i++) {
|
17192 | buf[i] = str.charCodeAt(i);
|
17193 | }
|
17194 | return buf;
|
17195 | };
|
17196 |
|
17197 |
|
17198 | // convert array to string
|
17199 | exports.buf2string = function (buf, max) {
|
17200 | var i, out, c, c_len;
|
17201 | var len = max || buf.length;
|
17202 |
|
17203 | // Reserve max possible length (2 words per char)
|
17204 | // NB: by unknown reasons, Array is significantly faster for
|
17205 | // String.fromCharCode.apply than Uint16Array.
|
17206 | var utf16buf = new Array(len*2);
|
17207 |
|
17208 | for (out=0, i=0; i<len;) {
|
17209 | c = buf[i++];
|
17210 | // quick process ascii
|
17211 | if (c < 0x80) { utf16buf[out++] = c; continue; }
|
17212 |
|
17213 | c_len = _utf8len[c];
|
17214 | // skip 5 & 6 byte codes
|
17215 | if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
|
17216 |
|
17217 | // apply mask on first byte
|
17218 | c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
|
17219 | // join the rest
|
17220 | while (c_len > 1 && i < len) {
|
17221 | c = (c << 6) | (buf[i++] & 0x3f);
|
17222 | c_len--;
|
17223 | }
|
17224 |
|
17225 | // terminated by end of string?
|
17226 | if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
|
17227 |
|
17228 | if (c < 0x10000) {
|
17229 | utf16buf[out++] = c;
|
17230 | } else {
|
17231 | c -= 0x10000;
|
17232 | utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
|
17233 | utf16buf[out++] = 0xdc00 | (c & 0x3ff);
|
17234 | }
|
17235 | }
|
17236 |
|
17237 | return buf2binstring(utf16buf, out);
|
17238 | };
|
17239 |
|
17240 |
|
17241 | // Calculate max possible position in utf8 buffer,
|
17242 | // that will not break sequence. If that's not possible
|
17243 | // - (very small limits) return max size as is.
|
17244 | //
|
17245 | // buf[] - utf8 bytes array
|
17246 | // max - length limit (mandatory);
|
17247 | exports.utf8border = function(buf, max) {
|
17248 | var pos;
|
17249 |
|
17250 | max = max || buf.length;
|
17251 | if (max > buf.length) { max = buf.length; }
|
17252 |
|
17253 | // go back from last position, until start of sequence found
|
17254 | pos = max-1;
|
17255 | while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
|
17256 |
|
17257 | // Fuckup - very small and broken sequence,
|
17258 | // return max, because we should return something anyway.
|
17259 | if (pos < 0) { return max; }
|
17260 |
|
17261 | // If we came to start of buffer - that means vuffer is too small,
|
17262 | // return max too.
|
17263 | if (pos === 0) { return max; }
|
17264 |
|
17265 | return (pos + _utf8len[buf[pos]] > max) ? pos : max;
|
17266 | };
|
17267 |
|
17268 | },{"./common":14}],16:[function(require,module,exports){
|
17269 | 'use strict';
|
17270 |
|
17271 | // Note: adler32 takes 12% for level 0 and 2% for level 6.
|
17272 | // It doesn't worth to make additional optimizationa as in original.
|
17273 | // Small size is preferable.
|
17274 |
|
17275 | function adler32(adler, buf, len, pos) {
|
17276 | var s1 = (adler & 0xffff) |0,
|
17277 | s2 = ((adler >>> 16) & 0xffff) |0,
|
17278 | n = 0;
|
17279 |
|
17280 | while (len !== 0) {
|
17281 | // Set limit ~ twice less than 5552, to keep
|
17282 | // s2 in 31-bits, because we force signed ints.
|
17283 | // in other case %= will fail.
|
17284 | n = len > 2000 ? 2000 : len;
|
17285 | len -= n;
|
17286 |
|
17287 | do {
|
17288 | s1 = (s1 + buf[pos++]) |0;
|
17289 | s2 = (s2 + s1) |0;
|
17290 | } while (--n);
|
17291 |
|
17292 | s1 %= 65521;
|
17293 | s2 %= 65521;
|
17294 | }
|
17295 |
|
17296 | return (s1 | (s2 << 16)) |0;
|
17297 | }
|
17298 |
|
17299 |
|
17300 | module.exports = adler32;
|
17301 |
|
17302 | },{}],17:[function(require,module,exports){
|
17303 | module.exports = {
|
17304 |
|
17305 | /* Allowed flush values; see deflate() and inflate() below for details */
|
17306 | Z_NO_FLUSH: 0,
|
17307 | Z_PARTIAL_FLUSH: 1,
|
17308 | Z_SYNC_FLUSH: 2,
|
17309 | Z_FULL_FLUSH: 3,
|
17310 | Z_FINISH: 4,
|
17311 | Z_BLOCK: 5,
|
17312 | Z_TREES: 6,
|
17313 |
|
17314 | /* Return codes for the compression/decompression functions. Negative values
|
17315 | * are errors, positive values are used for special but normal events.
|
17316 | */
|
17317 | Z_OK: 0,
|
17318 | Z_STREAM_END: 1,
|
17319 | Z_NEED_DICT: 2,
|
17320 | Z_ERRNO: -1,
|
17321 | Z_STREAM_ERROR: -2,
|
17322 | Z_DATA_ERROR: -3,
|
17323 | //Z_MEM_ERROR: -4,
|
17324 | Z_BUF_ERROR: -5,
|
17325 | //Z_VERSION_ERROR: -6,
|
17326 |
|
17327 | /* compression levels */
|
17328 | Z_NO_COMPRESSION: 0,
|
17329 | Z_BEST_SPEED: 1,
|
17330 | Z_BEST_COMPRESSION: 9,
|
17331 | Z_DEFAULT_COMPRESSION: -1,
|
17332 |
|
17333 |
|
17334 | Z_FILTERED: 1,
|
17335 | Z_HUFFMAN_ONLY: 2,
|
17336 | Z_RLE: 3,
|
17337 | Z_FIXED: 4,
|
17338 | Z_DEFAULT_STRATEGY: 0,
|
17339 |
|
17340 | /* Possible values of the data_type field (though see inflate()) */
|
17341 | Z_BINARY: 0,
|
17342 | Z_TEXT: 1,
|
17343 | //Z_ASCII: 1, // = Z_TEXT (deprecated)
|
17344 | Z_UNKNOWN: 2,
|
17345 |
|
17346 | /* The deflate compression method */
|
17347 | Z_DEFLATED: 8
|
17348 | //Z_NULL: null // Use -1 or null inline, depending on var type
|
17349 | };
|
17350 |
|
17351 | },{}],18:[function(require,module,exports){
|
17352 | 'use strict';
|
17353 |
|
17354 | // Note: we can't get significant speed boost here.
|
17355 | // So write code to minimize size - no pregenerated tables
|
17356 | // and array tools dependencies.
|
17357 |
|
17358 |
|
17359 | // Use ordinary array, since untyped makes no boost here
|
17360 | function makeTable() {
|
17361 | var c, table = [];
|
17362 |
|
17363 | for (var n =0; n < 256; n++) {
|
17364 | c = n;
|
17365 | for (var k =0; k < 8; k++) {
|
17366 | c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
|
17367 | }
|
17368 | table[n] = c;
|
17369 | }
|
17370 |
|
17371 | return table;
|
17372 | }
|
17373 |
|
17374 | // Create table on load. Just 255 signed longs. Not a problem.
|
17375 | var crcTable = makeTable();
|
17376 |
|
17377 |
|
17378 | function crc32(crc, buf, len, pos) {
|
17379 | var t = crcTable,
|
17380 | end = pos + len;
|
17381 |
|
17382 | crc = crc ^ (-1);
|
17383 |
|
17384 | for (var i = pos; i < end; i++) {
|
17385 | crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
|
17386 | }
|
17387 |
|
17388 | return (crc ^ (-1)); // >>> 0;
|
17389 | }
|
17390 |
|
17391 |
|
17392 | module.exports = crc32;
|
17393 |
|
17394 | },{}],19:[function(require,module,exports){
|
17395 | 'use strict';
|
17396 |
|
17397 | var utils = require('../utils/common');
|
17398 | var trees = require('./trees');
|
17399 | var adler32 = require('./adler32');
|
17400 | var crc32 = require('./crc32');
|
17401 | var msg = require('./messages');
|
17402 |
|
17403 | /* Public constants ==========================================================*/
|
17404 | /* ===========================================================================*/
|
17405 |
|
17406 |
|
17407 | /* Allowed flush values; see deflate() and inflate() below for details */
|
17408 | var Z_NO_FLUSH = 0;
|
17409 | var Z_PARTIAL_FLUSH = 1;
|
17410 | //var Z_SYNC_FLUSH = 2;
|
17411 | var Z_FULL_FLUSH = 3;
|
17412 | var Z_FINISH = 4;
|
17413 | var Z_BLOCK = 5;
|
17414 | //var Z_TREES = 6;
|
17415 |
|
17416 |
|
17417 | /* Return codes for the compression/decompression functions. Negative values
|
17418 | * are errors, positive values are used for special but normal events.
|
17419 | */
|
17420 | var Z_OK = 0;
|
17421 | var Z_STREAM_END = 1;
|
17422 | //var Z_NEED_DICT = 2;
|
17423 | //var Z_ERRNO = -1;
|
17424 | var Z_STREAM_ERROR = -2;
|
17425 | var Z_DATA_ERROR = -3;
|
17426 | //var Z_MEM_ERROR = -4;
|
17427 | var Z_BUF_ERROR = -5;
|
17428 | //var Z_VERSION_ERROR = -6;
|
17429 |
|
17430 |
|
17431 | /* compression levels */
|
17432 | //var Z_NO_COMPRESSION = 0;
|
17433 | //var Z_BEST_SPEED = 1;
|
17434 | //var Z_BEST_COMPRESSION = 9;
|
17435 | var Z_DEFAULT_COMPRESSION = -1;
|
17436 |
|
17437 |
|
17438 | var Z_FILTERED = 1;
|
17439 | var Z_HUFFMAN_ONLY = 2;
|
17440 | var Z_RLE = 3;
|
17441 | var Z_FIXED = 4;
|
17442 | var Z_DEFAULT_STRATEGY = 0;
|
17443 |
|
17444 | /* Possible values of the data_type field (though see inflate()) */
|
17445 | //var Z_BINARY = 0;
|
17446 | //var Z_TEXT = 1;
|
17447 | //var Z_ASCII = 1; // = Z_TEXT
|
17448 | var Z_UNKNOWN = 2;
|
17449 |
|
17450 |
|
17451 | /* The deflate compression method */
|
17452 | var Z_DEFLATED = 8;
|
17453 |
|
17454 | /*============================================================================*/
|
17455 |
|
17456 |
|
17457 | var MAX_MEM_LEVEL = 9;
|
17458 | /* Maximum value for memLevel in deflateInit2 */
|
17459 | var MAX_WBITS = 15;
|
17460 | /* 32K LZ77 window */
|
17461 | var DEF_MEM_LEVEL = 8;
|
17462 |
|
17463 |
|
17464 | var LENGTH_CODES = 29;
|
17465 | /* number of length codes, not counting the special END_BLOCK code */
|
17466 | var LITERALS = 256;
|
17467 | /* number of literal bytes 0..255 */
|
17468 | var L_CODES = LITERALS + 1 + LENGTH_CODES;
|
17469 | /* number of Literal or Length codes, including the END_BLOCK code */
|
17470 | var D_CODES = 30;
|
17471 | /* number of distance codes */
|
17472 | var BL_CODES = 19;
|
17473 | /* number of codes used to transfer the bit lengths */
|
17474 | var HEAP_SIZE = 2*L_CODES + 1;
|
17475 | /* maximum heap size */
|
17476 | var MAX_BITS = 15;
|
17477 | /* All codes must not exceed MAX_BITS bits */
|
17478 |
|
17479 | var MIN_MATCH = 3;
|
17480 | var MAX_MATCH = 258;
|
17481 | var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
|
17482 |
|
17483 | var PRESET_DICT = 0x20;
|
17484 |
|
17485 | var INIT_STATE = 42;
|
17486 | var EXTRA_STATE = 69;
|
17487 | var NAME_STATE = 73;
|
17488 | var COMMENT_STATE = 91;
|
17489 | var HCRC_STATE = 103;
|
17490 | var BUSY_STATE = 113;
|
17491 | var FINISH_STATE = 666;
|
17492 |
|
17493 | var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
|
17494 | var BS_BLOCK_DONE = 2; /* block flush performed */
|
17495 | var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
|
17496 | var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
|
17497 |
|
17498 | var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
|
17499 |
|
17500 | function err(strm, errorCode) {
|
17501 | strm.msg = msg[errorCode];
|
17502 | return errorCode;
|
17503 | }
|
17504 |
|
17505 | function rank(f) {
|
17506 | return ((f) << 1) - ((f) > 4 ? 9 : 0);
|
17507 | }
|
17508 |
|
17509 | function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
|
17510 |
|
17511 |
|
17512 | /* =========================================================================
|
17513 | * Flush as much pending output as possible. All deflate() output goes
|
17514 | * through this function so some applications may wish to modify it
|
17515 | * to avoid allocating a large strm->output buffer and copying into it.
|
17516 | * (See also read_buf()).
|
17517 | */
|
17518 | function flush_pending(strm) {
|
17519 | var s = strm.state;
|
17520 |
|
17521 | //_tr_flush_bits(s);
|
17522 | var len = s.pending;
|
17523 | if (len > strm.avail_out) {
|
17524 | len = strm.avail_out;
|
17525 | }
|
17526 | if (len === 0) { return; }
|
17527 |
|
17528 | utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
|
17529 | strm.next_out += len;
|
17530 | s.pending_out += len;
|
17531 | strm.total_out += len;
|
17532 | strm.avail_out -= len;
|
17533 | s.pending -= len;
|
17534 | if (s.pending === 0) {
|
17535 | s.pending_out = 0;
|
17536 | }
|
17537 | }
|
17538 |
|
17539 |
|
17540 | function flush_block_only (s, last) {
|
17541 | trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
|
17542 | s.block_start = s.strstart;
|
17543 | flush_pending(s.strm);
|
17544 | }
|
17545 |
|
17546 |
|
17547 | function put_byte(s, b) {
|
17548 | s.pending_buf[s.pending++] = b;
|
17549 | }
|
17550 |
|
17551 |
|
17552 | /* =========================================================================
|
17553 | * Put a short in the pending buffer. The 16-bit value is put in MSB order.
|
17554 | * IN assertion: the stream state is correct and there is enough room in
|
17555 | * pending_buf.
|
17556 | */
|
17557 | function putShortMSB(s, b) {
|
17558 | // put_byte(s, (Byte)(b >> 8));
|
17559 | // put_byte(s, (Byte)(b & 0xff));
|
17560 | s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
|
17561 | s.pending_buf[s.pending++] = b & 0xff;
|
17562 | }
|
17563 |
|
17564 |
|
17565 | /* ===========================================================================
|
17566 | * Read a new buffer from the current input stream, update the adler32
|
17567 | * and total number of bytes read. All deflate() input goes through
|
17568 | * this function so some applications may wish to modify it to avoid
|
17569 | * allocating a large strm->input buffer and copying from it.
|
17570 | * (See also flush_pending()).
|
17571 | */
|
17572 | function read_buf(strm, buf, start, size) {
|
17573 | var len = strm.avail_in;
|
17574 |
|
17575 | if (len > size) { len = size; }
|
17576 | if (len === 0) { return 0; }
|
17577 |
|
17578 | strm.avail_in -= len;
|
17579 |
|
17580 | utils.arraySet(buf, strm.input, strm.next_in, len, start);
|
17581 | if (strm.state.wrap === 1) {
|
17582 | strm.adler = adler32(strm.adler, buf, len, start);
|
17583 | }
|
17584 |
|
17585 | else if (strm.state.wrap === 2) {
|
17586 | strm.adler = crc32(strm.adler, buf, len, start);
|
17587 | }
|
17588 |
|
17589 | strm.next_in += len;
|
17590 | strm.total_in += len;
|
17591 |
|
17592 | return len;
|
17593 | }
|
17594 |
|
17595 |
|
17596 | /* ===========================================================================
|
17597 | * Set match_start to the longest match starting at the given string and
|
17598 | * return its length. Matches shorter or equal to prev_length are discarded,
|
17599 | * in which case the result is equal to prev_length and match_start is
|
17600 | * garbage.
|
17601 | * IN assertions: cur_match is the head of the hash chain for the current
|
17602 | * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
|
17603 | * OUT assertion: the match length is not greater than s->lookahead.
|
17604 | */
|
17605 | function longest_match(s, cur_match) {
|
17606 | var chain_length = s.max_chain_length; /* max hash chain length */
|
17607 | var scan = s.strstart; /* current string */
|
17608 | var match; /* matched string */
|
17609 | var len; /* length of current match */
|
17610 | var best_len = s.prev_length; /* best match length so far */
|
17611 | var nice_match = s.nice_match; /* stop if match long enough */
|
17612 | var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
|
17613 | s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
|
17614 |
|
17615 | var _win = s.window; // shortcut
|
17616 |
|
17617 | var wmask = s.w_mask;
|
17618 | var prev = s.prev;
|
17619 |
|
17620 | /* Stop when cur_match becomes <= limit. To simplify the code,
|
17621 | * we prevent matches with the string of window index 0.
|
17622 | */
|
17623 |
|
17624 | var strend = s.strstart + MAX_MATCH;
|
17625 | var scan_end1 = _win[scan + best_len - 1];
|
17626 | var scan_end = _win[scan + best_len];
|
17627 |
|
17628 | /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
|
17629 | * It is easy to get rid of this optimization if necessary.
|
17630 | */
|
17631 | // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
|
17632 |
|
17633 | /* Do not waste too much time if we already have a good match: */
|
17634 | if (s.prev_length >= s.good_match) {
|
17635 | chain_length >>= 2;
|
17636 | }
|
17637 | /* Do not look for matches beyond the end of the input. This is necessary
|
17638 | * to make deflate deterministic.
|
17639 | */
|
17640 | if (nice_match > s.lookahead) { nice_match = s.lookahead; }
|
17641 |
|
17642 | // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
|
17643 |
|
17644 | do {
|
17645 | // Assert(cur_match < s->strstart, "no future");
|
17646 | match = cur_match;
|
17647 |
|
17648 | /* Skip to next match if the match length cannot increase
|
17649 | * or if the match length is less than 2. Note that the checks below
|
17650 | * for insufficient lookahead only occur occasionally for performance
|
17651 | * reasons. Therefore uninitialized memory will be accessed, and
|
17652 | * conditional jumps will be made that depend on those values.
|
17653 | * However the length of the match is limited to the lookahead, so
|
17654 | * the output of deflate is not affected by the uninitialized values.
|
17655 | */
|
17656 |
|
17657 | if (_win[match + best_len] !== scan_end ||
|
17658 | _win[match + best_len - 1] !== scan_end1 ||
|
17659 | _win[match] !== _win[scan] ||
|
17660 | _win[++match] !== _win[scan + 1]) {
|
17661 | continue;
|
17662 | }
|
17663 |
|
17664 | /* The check at best_len-1 can be removed because it will be made
|
17665 | * again later. (This heuristic is not always a win.)
|
17666 | * It is not necessary to compare scan[2] and match[2] since they
|
17667 | * are always equal when the other bytes match, given that
|
17668 | * the hash keys are equal and that HASH_BITS >= 8.
|
17669 | */
|
17670 | scan += 2;
|
17671 | match++;
|
17672 | // Assert(*scan == *match, "match[2]?");
|
17673 |
|
17674 | /* We check for insufficient lookahead only every 8th comparison;
|
17675 | * the 256th check will be made at strstart+258.
|
17676 | */
|
17677 | do {
|
17678 | /*jshint noempty:false*/
|
17679 | } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
|
17680 | _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
|
17681 | _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
|
17682 | _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
|
17683 | scan < strend);
|
17684 |
|
17685 | // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
|
17686 |
|
17687 | len = MAX_MATCH - (strend - scan);
|
17688 | scan = strend - MAX_MATCH;
|
17689 |
|
17690 | if (len > best_len) {
|
17691 | s.match_start = cur_match;
|
17692 | best_len = len;
|
17693 | if (len >= nice_match) {
|
17694 | break;
|
17695 | }
|
17696 | scan_end1 = _win[scan + best_len - 1];
|
17697 | scan_end = _win[scan + best_len];
|
17698 | }
|
17699 | } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
|
17700 |
|
17701 | if (best_len <= s.lookahead) {
|
17702 | return best_len;
|
17703 | }
|
17704 | return s.lookahead;
|
17705 | }
|
17706 |
|
17707 |
|
17708 | /* ===========================================================================
|
17709 | * Fill the window when the lookahead becomes insufficient.
|
17710 | * Updates strstart and lookahead.
|
17711 | *
|
17712 | * IN assertion: lookahead < MIN_LOOKAHEAD
|
17713 | * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
|
17714 | * At least one byte has been read, or avail_in == 0; reads are
|
17715 | * performed for at least two bytes (required for the zip translate_eol
|
17716 | * option -- not supported here).
|
17717 | */
|
17718 | function fill_window(s) {
|
17719 | var _w_size = s.w_size;
|
17720 | var p, n, m, more, str;
|
17721 |
|
17722 | //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
|
17723 |
|
17724 | do {
|
17725 | more = s.window_size - s.lookahead - s.strstart;
|
17726 |
|
17727 | // JS ints have 32 bit, block below not needed
|
17728 | /* Deal with !@#$% 64K limit: */
|
17729 | //if (sizeof(int) <= 2) {
|
17730 | // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
|
17731 | // more = wsize;
|
17732 | //
|
17733 | // } else if (more == (unsigned)(-1)) {
|
17734 | // /* Very unlikely, but possible on 16 bit machine if
|
17735 | // * strstart == 0 && lookahead == 1 (input done a byte at time)
|
17736 | // */
|
17737 | // more--;
|
17738 | // }
|
17739 | //}
|
17740 |
|
17741 |
|
17742 | /* If the window is almost full and there is insufficient lookahead,
|
17743 | * move the upper half to the lower one to make room in the upper half.
|
17744 | */
|
17745 | if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
|
17746 |
|
17747 | utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
|
17748 | s.match_start -= _w_size;
|
17749 | s.strstart -= _w_size;
|
17750 | /* we now have strstart >= MAX_DIST */
|
17751 | s.block_start -= _w_size;
|
17752 |
|
17753 | /* Slide the hash table (could be avoided with 32 bit values
|
17754 | at the expense of memory usage). We slide even when level == 0
|
17755 | to keep the hash table consistent if we switch back to level > 0
|
17756 | later. (Using level 0 permanently is not an optimal usage of
|
17757 | zlib, so we don't care about this pathological case.)
|
17758 | */
|
17759 |
|
17760 | n = s.hash_size;
|
17761 | p = n;
|
17762 | do {
|
17763 | m = s.head[--p];
|
17764 | s.head[p] = (m >= _w_size ? m - _w_size : 0);
|
17765 | } while (--n);
|
17766 |
|
17767 | n = _w_size;
|
17768 | p = n;
|
17769 | do {
|
17770 | m = s.prev[--p];
|
17771 | s.prev[p] = (m >= _w_size ? m - _w_size : 0);
|
17772 | /* If n is not on any hash chain, prev[n] is garbage but
|
17773 | * its value will never be used.
|
17774 | */
|
17775 | } while (--n);
|
17776 |
|
17777 | more += _w_size;
|
17778 | }
|
17779 | if (s.strm.avail_in === 0) {
|
17780 | break;
|
17781 | }
|
17782 |
|
17783 | /* If there was no sliding:
|
17784 | * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
|
17785 | * more == window_size - lookahead - strstart
|
17786 | * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
|
17787 | * => more >= window_size - 2*WSIZE + 2
|
17788 | * In the BIG_MEM or MMAP case (not yet supported),
|
17789 | * window_size == input_size + MIN_LOOKAHEAD &&
|
17790 | * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
|
17791 | * Otherwise, window_size == 2*WSIZE so more >= 2.
|
17792 | * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
|
17793 | */
|
17794 | //Assert(more >= 2, "more < 2");
|
17795 | n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
|
17796 | s.lookahead += n;
|
17797 |
|
17798 | /* Initialize the hash value now that we have some input: */
|
17799 | if (s.lookahead + s.insert >= MIN_MATCH) {
|
17800 | str = s.strstart - s.insert;
|
17801 | s.ins_h = s.window[str];
|
17802 |
|
17803 | /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
|
17804 | s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
|
17805 | //#if MIN_MATCH != 3
|
17806 | // Call update_hash() MIN_MATCH-3 more times
|
17807 | //#endif
|
17808 | while (s.insert) {
|
17809 | /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
|
17810 | s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
|
17811 |
|
17812 | s.prev[str & s.w_mask] = s.head[s.ins_h];
|
17813 | s.head[s.ins_h] = str;
|
17814 | str++;
|
17815 | s.insert--;
|
17816 | if (s.lookahead + s.insert < MIN_MATCH) {
|
17817 | break;
|
17818 | }
|
17819 | }
|
17820 | }
|
17821 | /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
|
17822 | * but this is not important since only literal bytes will be emitted.
|
17823 | */
|
17824 |
|
17825 | } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
|
17826 |
|
17827 | /* If the WIN_INIT bytes after the end of the current data have never been
|
17828 | * written, then zero those bytes in order to avoid memory check reports of
|
17829 | * the use of uninitialized (or uninitialised as Julian writes) bytes by
|
17830 | * the longest match routines. Update the high water mark for the next
|
17831 | * time through here. WIN_INIT is set to MAX_MATCH since the longest match
|
17832 | * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
|
17833 | */
|
17834 | // if (s.high_water < s.window_size) {
|
17835 | // var curr = s.strstart + s.lookahead;
|
17836 | // var init = 0;
|
17837 | //
|
17838 | // if (s.high_water < curr) {
|
17839 | // /* Previous high water mark below current data -- zero WIN_INIT
|
17840 | // * bytes or up to end of window, whichever is less.
|
17841 | // */
|
17842 | // init = s.window_size - curr;
|
17843 | // if (init > WIN_INIT)
|
17844 | // init = WIN_INIT;
|
17845 | // zmemzero(s->window + curr, (unsigned)init);
|
17846 | // s->high_water = curr + init;
|
17847 | // }
|
17848 | // else if (s->high_water < (ulg)curr + WIN_INIT) {
|
17849 | // /* High water mark at or above current data, but below current data
|
17850 | // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
|
17851 | // * to end of window, whichever is less.
|
17852 | // */
|
17853 | // init = (ulg)curr + WIN_INIT - s->high_water;
|
17854 | // if (init > s->window_size - s->high_water)
|
17855 | // init = s->window_size - s->high_water;
|
17856 | // zmemzero(s->window + s->high_water, (unsigned)init);
|
17857 | // s->high_water += init;
|
17858 | // }
|
17859 | // }
|
17860 | //
|
17861 | // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
|
17862 | // "not enough room for search");
|
17863 | }
|
17864 |
|
17865 | /* ===========================================================================
|
17866 | * Copy without compression as much as possible from the input stream, return
|
17867 | * the current block state.
|
17868 | * This function does not insert new strings in the dictionary since
|
17869 | * uncompressible data is probably not useful. This function is used
|
17870 | * only for the level=0 compression option.
|
17871 | * NOTE: this function should be optimized to avoid extra copying from
|
17872 | * window to pending_buf.
|
17873 | */
|
17874 | function deflate_stored(s, flush) {
|
17875 | /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
|
17876 | * to pending_buf_size, and each stored block has a 5 byte header:
|
17877 | */
|
17878 | var max_block_size = 0xffff;
|
17879 |
|
17880 | if (max_block_size > s.pending_buf_size - 5) {
|
17881 | max_block_size = s.pending_buf_size - 5;
|
17882 | }
|
17883 |
|
17884 | /* Copy as much as possible from input to output: */
|
17885 | for (;;) {
|
17886 | /* Fill the window as much as possible: */
|
17887 | if (s.lookahead <= 1) {
|
17888 |
|
17889 | //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
|
17890 | // s->block_start >= (long)s->w_size, "slide too late");
|
17891 | // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
|
17892 | // s.block_start >= s.w_size)) {
|
17893 | // throw new Error("slide too late");
|
17894 | // }
|
17895 |
|
17896 | fill_window(s);
|
17897 | if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
|
17898 | return BS_NEED_MORE;
|
17899 | }
|
17900 |
|
17901 | if (s.lookahead === 0) {
|
17902 | break;
|
17903 | }
|
17904 | /* flush the current block */
|
17905 | }
|
17906 | //Assert(s->block_start >= 0L, "block gone");
|
17907 | // if (s.block_start < 0) throw new Error("block gone");
|
17908 |
|
17909 | s.strstart += s.lookahead;
|
17910 | s.lookahead = 0;
|
17911 |
|
17912 | /* Emit a stored block if pending_buf will be full: */
|
17913 | var max_start = s.block_start + max_block_size;
|
17914 |
|
17915 | if (s.strstart === 0 || s.strstart >= max_start) {
|
17916 | /* strstart == 0 is possible when wraparound on 16-bit machine */
|
17917 | s.lookahead = s.strstart - max_start;
|
17918 | s.strstart = max_start;
|
17919 | /*** FLUSH_BLOCK(s, 0); ***/
|
17920 | flush_block_only(s, false);
|
17921 | if (s.strm.avail_out === 0) {
|
17922 | return BS_NEED_MORE;
|
17923 | }
|
17924 | /***/
|
17925 |
|
17926 |
|
17927 | }
|
17928 | /* Flush if we may have to slide, otherwise block_start may become
|
17929 | * negative and the data will be gone:
|
17930 | */
|
17931 | if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
|
17932 | /*** FLUSH_BLOCK(s, 0); ***/
|
17933 | flush_block_only(s, false);
|
17934 | if (s.strm.avail_out === 0) {
|
17935 | return BS_NEED_MORE;
|
17936 | }
|
17937 | /***/
|
17938 | }
|
17939 | }
|
17940 |
|
17941 | s.insert = 0;
|
17942 |
|
17943 | if (flush === Z_FINISH) {
|
17944 | /*** FLUSH_BLOCK(s, 1); ***/
|
17945 | flush_block_only(s, true);
|
17946 | if (s.strm.avail_out === 0) {
|
17947 | return BS_FINISH_STARTED;
|
17948 | }
|
17949 | /***/
|
17950 | return BS_FINISH_DONE;
|
17951 | }
|
17952 |
|
17953 | if (s.strstart > s.block_start) {
|
17954 | /*** FLUSH_BLOCK(s, 0); ***/
|
17955 | flush_block_only(s, false);
|
17956 | if (s.strm.avail_out === 0) {
|
17957 | return BS_NEED_MORE;
|
17958 | }
|
17959 | /***/
|
17960 | }
|
17961 |
|
17962 | return BS_NEED_MORE;
|
17963 | }
|
17964 |
|
17965 | /* ===========================================================================
|
17966 | * Compress as much as possible from the input stream, return the current
|
17967 | * block state.
|
17968 | * This function does not perform lazy evaluation of matches and inserts
|
17969 | * new strings in the dictionary only for unmatched strings or for short
|
17970 | * matches. It is used only for the fast compression options.
|
17971 | */
|
17972 | function deflate_fast(s, flush) {
|
17973 | var hash_head; /* head of the hash chain */
|
17974 | var bflush; /* set if current block must be flushed */
|
17975 |
|
17976 | for (;;) {
|
17977 | /* Make sure that we always have enough lookahead, except
|
17978 | * at the end of the input file. We need MAX_MATCH bytes
|
17979 | * for the next match, plus MIN_MATCH bytes to insert the
|
17980 | * string following the next match.
|
17981 | */
|
17982 | if (s.lookahead < MIN_LOOKAHEAD) {
|
17983 | fill_window(s);
|
17984 | if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
|
17985 | return BS_NEED_MORE;
|
17986 | }
|
17987 | if (s.lookahead === 0) {
|
17988 | break; /* flush the current block */
|
17989 | }
|
17990 | }
|
17991 |
|
17992 | /* Insert the string window[strstart .. strstart+2] in the
|
17993 | * dictionary, and set hash_head to the head of the hash chain:
|
17994 | */
|
17995 | hash_head = 0/*NIL*/;
|
17996 | if (s.lookahead >= MIN_MATCH) {
|
17997 | /*** INSERT_STRING(s, s.strstart, hash_head); ***/
|
17998 | s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
|
17999 | hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
|
18000 | s.head[s.ins_h] = s.strstart;
|
18001 | /***/
|
18002 | }
|
18003 |
|
18004 | /* Find the longest match, discarding those <= prev_length.
|
18005 | * At this point we have always match_length < MIN_MATCH
|
18006 | */
|
18007 | if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
|
18008 | /* To simplify the code, we prevent matches with the string
|
18009 | * of window index 0 (in particular we have to avoid a match
|
18010 | * of the string with itself at the start of the input file).
|
18011 | */
|
18012 | s.match_length = longest_match(s, hash_head);
|
18013 | /* longest_match() sets match_start */
|
18014 | }
|
18015 | if (s.match_length >= MIN_MATCH) {
|
18016 | // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
|
18017 |
|
18018 | /*** _tr_tally_dist(s, s.strstart - s.match_start,
|
18019 | s.match_length - MIN_MATCH, bflush); ***/
|
18020 | bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
|
18021 |
|
18022 | s.lookahead -= s.match_length;
|
18023 |
|
18024 | /* Insert new strings in the hash table only if the match length
|
18025 | * is not too large. This saves time but degrades compression.
|
18026 | */
|
18027 | if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
|
18028 | s.match_length--; /* string at strstart already in table */
|
18029 | do {
|
18030 | s.strstart++;
|
18031 | /*** INSERT_STRING(s, s.strstart, hash_head); ***/
|
18032 | s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
|
18033 | hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
|
18034 | s.head[s.ins_h] = s.strstart;
|
18035 | /***/
|
18036 | /* strstart never exceeds WSIZE-MAX_MATCH, so there are
|
18037 | * always MIN_MATCH bytes ahead.
|
18038 | */
|
18039 | } while (--s.match_length !== 0);
|
18040 | s.strstart++;
|
18041 | } else
|
18042 | {
|
18043 | s.strstart += s.match_length;
|
18044 | s.match_length = 0;
|
18045 | s.ins_h = s.window[s.strstart];
|
18046 | /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
|
18047 | s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
|
18048 |
|
18049 | //#if MIN_MATCH != 3
|
18050 | // Call UPDATE_HASH() MIN_MATCH-3 more times
|
18051 | //#endif
|
18052 | /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
|
18053 | * matter since it will be recomputed at next deflate call.
|
18054 | */
|
18055 | }
|
18056 | } else {
|
18057 | /* No match, output a literal byte */
|
18058 | //Tracevv((stderr,"%c", s.window[s.strstart]));
|
18059 | /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
|
18060 | bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
|
18061 |
|
18062 | s.lookahead--;
|
18063 | s.strstart++;
|
18064 | }
|
18065 | if (bflush) {
|
18066 | /*** FLUSH_BLOCK(s, 0); ***/
|
18067 | flush_block_only(s, false);
|
18068 | if (s.strm.avail_out === 0) {
|
18069 | return BS_NEED_MORE;
|
18070 | }
|
18071 | /***/
|
18072 | }
|
18073 | }
|
18074 | s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
|
18075 | if (flush === Z_FINISH) {
|
18076 | /*** FLUSH_BLOCK(s, 1); ***/
|
18077 | flush_block_only(s, true);
|
18078 | if (s.strm.avail_out === 0) {
|
18079 | return BS_FINISH_STARTED;
|
18080 | }
|
18081 | /***/
|
18082 | return BS_FINISH_DONE;
|
18083 | }
|
18084 | if (s.last_lit) {
|
18085 | /*** FLUSH_BLOCK(s, 0); ***/
|
18086 | flush_block_only(s, false);
|
18087 | if (s.strm.avail_out === 0) {
|
18088 | return BS_NEED_MORE;
|
18089 | }
|
18090 | /***/
|
18091 | }
|
18092 | return BS_BLOCK_DONE;
|
18093 | }
|
18094 |
|
18095 | /* ===========================================================================
|
18096 | * Same as above, but achieves better compression. We use a lazy
|
18097 | * evaluation for matches: a match is finally adopted only if there is
|
18098 | * no better match at the next window position.
|
18099 | */
|
18100 | function deflate_slow(s, flush) {
|
18101 | var hash_head; /* head of hash chain */
|
18102 | var bflush; /* set if current block must be flushed */
|
18103 |
|
18104 | var max_insert;
|
18105 |
|
18106 | /* Process the input block. */
|
18107 | for (;;) {
|
18108 | /* Make sure that we always have enough lookahead, except
|
18109 | * at the end of the input file. We need MAX_MATCH bytes
|
18110 | * for the next match, plus MIN_MATCH bytes to insert the
|
18111 | * string following the next match.
|
18112 | */
|
18113 | if (s.lookahead < MIN_LOOKAHEAD) {
|
18114 | fill_window(s);
|
18115 | if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
|
18116 | return BS_NEED_MORE;
|
18117 | }
|
18118 | if (s.lookahead === 0) { break; } /* flush the current block */
|
18119 | }
|
18120 |
|
18121 | /* Insert the string window[strstart .. strstart+2] in the
|
18122 | * dictionary, and set hash_head to the head of the hash chain:
|
18123 | */
|
18124 | hash_head = 0/*NIL*/;
|
18125 | if (s.lookahead >= MIN_MATCH) {
|
18126 | /*** INSERT_STRING(s, s.strstart, hash_head); ***/
|
18127 | s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
|
18128 | hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
|
18129 | s.head[s.ins_h] = s.strstart;
|
18130 | /***/
|
18131 | }
|
18132 |
|
18133 | /* Find the longest match, discarding those <= prev_length.
|
18134 | */
|
18135 | s.prev_length = s.match_length;
|
18136 | s.prev_match = s.match_start;
|
18137 | s.match_length = MIN_MATCH-1;
|
18138 |
|
18139 | if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
|
18140 | s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
|
18141 | /* To simplify the code, we prevent matches with the string
|
18142 | * of window index 0 (in particular we have to avoid a match
|
18143 | * of the string with itself at the start of the input file).
|
18144 | */
|
18145 | s.match_length = longest_match(s, hash_head);
|
18146 | /* longest_match() sets match_start */
|
18147 |
|
18148 | if (s.match_length <= 5 &&
|
18149 | (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
|
18150 |
|
18151 | /* If prev_match is also MIN_MATCH, match_start is garbage
|
18152 | * but we will ignore the current match anyway.
|
18153 | */
|
18154 | s.match_length = MIN_MATCH-1;
|
18155 | }
|
18156 | }
|
18157 | /* If there was a match at the previous step and the current
|
18158 | * match is not better, output the previous match:
|
18159 | */
|
18160 | if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
|
18161 | max_insert = s.strstart + s.lookahead - MIN_MATCH;
|
18162 | /* Do not insert strings in hash table beyond this. */
|
18163 |
|
18164 | //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
|
18165 |
|
18166 | /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
|
18167 | s.prev_length - MIN_MATCH, bflush);***/
|
18168 | bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
|
18169 | /* Insert in hash table all strings up to the end of the match.
|
18170 | * strstart-1 and strstart are already inserted. If there is not
|
18171 | * enough lookahead, the last two strings are not inserted in
|
18172 | * the hash table.
|
18173 | */
|
18174 | s.lookahead -= s.prev_length-1;
|
18175 | s.prev_length -= 2;
|
18176 | do {
|
18177 | if (++s.strstart <= max_insert) {
|
18178 | /*** INSERT_STRING(s, s.strstart, hash_head); ***/
|
18179 | s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
|
18180 | hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
|
18181 | s.head[s.ins_h] = s.strstart;
|
18182 | /***/
|
18183 | }
|
18184 | } while (--s.prev_length !== 0);
|
18185 | s.match_available = 0;
|
18186 | s.match_length = MIN_MATCH-1;
|
18187 | s.strstart++;
|
18188 |
|
18189 | if (bflush) {
|
18190 | /*** FLUSH_BLOCK(s, 0); ***/
|
18191 | flush_block_only(s, false);
|
18192 | if (s.strm.avail_out === 0) {
|
18193 | return BS_NEED_MORE;
|
18194 | }
|
18195 | /***/
|
18196 | }
|
18197 |
|
18198 | } else if (s.match_available) {
|
18199 | /* If there was no match at the previous position, output a
|
18200 | * single literal. If there was a match but the current match
|
18201 | * is longer, truncate the previous match to a single literal.
|
18202 | */
|
18203 | //Tracevv((stderr,"%c", s->window[s->strstart-1]));
|
18204 | /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
|
18205 | bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
|
18206 |
|
18207 | if (bflush) {
|
18208 | /*** FLUSH_BLOCK_ONLY(s, 0) ***/
|
18209 | flush_block_only(s, false);
|
18210 | /***/
|
18211 | }
|
18212 | s.strstart++;
|
18213 | s.lookahead--;
|
18214 | if (s.strm.avail_out === 0) {
|
18215 | return BS_NEED_MORE;
|
18216 | }
|
18217 | } else {
|
18218 | /* There is no previous match to compare with, wait for
|
18219 | * the next step to decide.
|
18220 | */
|
18221 | s.match_available = 1;
|
18222 | s.strstart++;
|
18223 | s.lookahead--;
|
18224 | }
|
18225 | }
|
18226 | //Assert (flush != Z_NO_FLUSH, "no flush?");
|
18227 | if (s.match_available) {
|
18228 | //Tracevv((stderr,"%c", s->window[s->strstart-1]));
|
18229 | /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
|
18230 | bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
|
18231 |
|
18232 | s.match_available = 0;
|
18233 | }
|
18234 | s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
|
18235 | if (flush === Z_FINISH) {
|
18236 | /*** FLUSH_BLOCK(s, 1); ***/
|
18237 | flush_block_only(s, true);
|
18238 | if (s.strm.avail_out === 0) {
|
18239 | return BS_FINISH_STARTED;
|
18240 | }
|
18241 | /***/
|
18242 | return BS_FINISH_DONE;
|
18243 | }
|
18244 | if (s.last_lit) {
|
18245 | /*** FLUSH_BLOCK(s, 0); ***/
|
18246 | flush_block_only(s, false);
|
18247 | if (s.strm.avail_out === 0) {
|
18248 | return BS_NEED_MORE;
|
18249 | }
|
18250 | /***/
|
18251 | }
|
18252 |
|
18253 | return BS_BLOCK_DONE;
|
18254 | }
|
18255 |
|
18256 |
|
18257 | /* ===========================================================================
|
18258 | * For Z_RLE, simply look for runs of bytes, generate matches only of distance
|
18259 | * one. Do not maintain a hash table. (It will be regenerated if this run of
|
18260 | * deflate switches away from Z_RLE.)
|
18261 | */
|
18262 | function deflate_rle(s, flush) {
|
18263 | var bflush; /* set if current block must be flushed */
|
18264 | var prev; /* byte at distance one to match */
|
18265 | var scan, strend; /* scan goes up to strend for length of run */
|
18266 |
|
18267 | var _win = s.window;
|
18268 |
|
18269 | for (;;) {
|
18270 | /* Make sure that we always have enough lookahead, except
|
18271 | * at the end of the input file. We need MAX_MATCH bytes
|
18272 | * for the longest run, plus one for the unrolled loop.
|
18273 | */
|
18274 | if (s.lookahead <= MAX_MATCH) {
|
18275 | fill_window(s);
|
18276 | if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
|
18277 | return BS_NEED_MORE;
|
18278 | }
|
18279 | if (s.lookahead === 0) { break; } /* flush the current block */
|
18280 | }
|
18281 |
|
18282 | /* See how many times the previous byte repeats */
|
18283 | s.match_length = 0;
|
18284 | if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
|
18285 | scan = s.strstart - 1;
|
18286 | prev = _win[scan];
|
18287 | if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
|
18288 | strend = s.strstart + MAX_MATCH;
|
18289 | do {
|
18290 | /*jshint noempty:false*/
|
18291 | } while (prev === _win[++scan] && prev === _win[++scan] &&
|
18292 | prev === _win[++scan] && prev === _win[++scan] &&
|
18293 | prev === _win[++scan] && prev === _win[++scan] &&
|
18294 | prev === _win[++scan] && prev === _win[++scan] &&
|
18295 | scan < strend);
|
18296 | s.match_length = MAX_MATCH - (strend - scan);
|
18297 | if (s.match_length > s.lookahead) {
|
18298 | s.match_length = s.lookahead;
|
18299 | }
|
18300 | }
|
18301 | //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
|
18302 | }
|
18303 |
|
18304 | /* Emit match if have run of MIN_MATCH or longer, else emit literal */
|
18305 | if (s.match_length >= MIN_MATCH) {
|
18306 | //check_match(s, s.strstart, s.strstart - 1, s.match_length);
|
18307 |
|
18308 | /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
|
18309 | bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
|
18310 |
|
18311 | s.lookahead -= s.match_length;
|
18312 | s.strstart += s.match_length;
|
18313 | s.match_length = 0;
|
18314 | } else {
|
18315 | /* No match, output a literal byte */
|
18316 | //Tracevv((stderr,"%c", s->window[s->strstart]));
|
18317 | /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
|
18318 | bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
|
18319 |
|
18320 | s.lookahead--;
|
18321 | s.strstart++;
|
18322 | }
|
18323 | if (bflush) {
|
18324 | /*** FLUSH_BLOCK(s, 0); ***/
|
18325 | flush_block_only(s, false);
|
18326 | if (s.strm.avail_out === 0) {
|
18327 | return BS_NEED_MORE;
|
18328 | }
|
18329 | /***/
|
18330 | }
|
18331 | }
|
18332 | s.insert = 0;
|
18333 | if (flush === Z_FINISH) {
|
18334 | /*** FLUSH_BLOCK(s, 1); ***/
|
18335 | flush_block_only(s, true);
|
18336 | if (s.strm.avail_out === 0) {
|
18337 | return BS_FINISH_STARTED;
|
18338 | }
|
18339 | /***/
|
18340 | return BS_FINISH_DONE;
|
18341 | }
|
18342 | if (s.last_lit) {
|
18343 | /*** FLUSH_BLOCK(s, 0); ***/
|
18344 | flush_block_only(s, false);
|
18345 | if (s.strm.avail_out === 0) {
|
18346 | return BS_NEED_MORE;
|
18347 | }
|
18348 | /***/
|
18349 | }
|
18350 | return BS_BLOCK_DONE;
|
18351 | }
|
18352 |
|
18353 | /* ===========================================================================
|
18354 | * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
|
18355 | * (It will be regenerated if this run of deflate switches away from Huffman.)
|
18356 | */
|
18357 | function deflate_huff(s, flush) {
|
18358 | var bflush; /* set if current block must be flushed */
|
18359 |
|
18360 | for (;;) {
|
18361 | /* Make sure that we have a literal to write. */
|
18362 | if (s.lookahead === 0) {
|
18363 | fill_window(s);
|
18364 | if (s.lookahead === 0) {
|
18365 | if (flush === Z_NO_FLUSH) {
|
18366 | return BS_NEED_MORE;
|
18367 | }
|
18368 | break; /* flush the current block */
|
18369 | }
|
18370 | }
|
18371 |
|
18372 | /* Output a literal byte */
|
18373 | s.match_length = 0;
|
18374 | //Tracevv((stderr,"%c", s->window[s->strstart]));
|
18375 | /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
|
18376 | bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
|
18377 | s.lookahead--;
|
18378 | s.strstart++;
|
18379 | if (bflush) {
|
18380 | /*** FLUSH_BLOCK(s, 0); ***/
|
18381 | flush_block_only(s, false);
|
18382 | if (s.strm.avail_out === 0) {
|
18383 | return BS_NEED_MORE;
|
18384 | }
|
18385 | /***/
|
18386 | }
|
18387 | }
|
18388 | s.insert = 0;
|
18389 | if (flush === Z_FINISH) {
|
18390 | /*** FLUSH_BLOCK(s, 1); ***/
|
18391 | flush_block_only(s, true);
|
18392 | if (s.strm.avail_out === 0) {
|
18393 | return BS_FINISH_STARTED;
|
18394 | }
|
18395 | /***/
|
18396 | return BS_FINISH_DONE;
|
18397 | }
|
18398 | if (s.last_lit) {
|
18399 | /*** FLUSH_BLOCK(s, 0); ***/
|
18400 | flush_block_only(s, false);
|
18401 | if (s.strm.avail_out === 0) {
|
18402 | return BS_NEED_MORE;
|
18403 | }
|
18404 | /***/
|
18405 | }
|
18406 | return BS_BLOCK_DONE;
|
18407 | }
|
18408 |
|
18409 | /* Values for max_lazy_match, good_match and max_chain_length, depending on
|
18410 | * the desired pack level (0..9). The values given below have been tuned to
|
18411 | * exclude worst case performance for pathological files. Better values may be
|
18412 | * found for specific files.
|
18413 | */
|
18414 | var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
|
18415 | this.good_length = good_length;
|
18416 | this.max_lazy = max_lazy;
|
18417 | this.nice_length = nice_length;
|
18418 | this.max_chain = max_chain;
|
18419 | this.func = func;
|
18420 | };
|
18421 |
|
18422 | var configuration_table;
|
18423 |
|
18424 | configuration_table = [
|
18425 | /* good lazy nice chain */
|
18426 | new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
|
18427 | new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
|
18428 | new Config(4, 5, 16, 8, deflate_fast), /* 2 */
|
18429 | new Config(4, 6, 32, 32, deflate_fast), /* 3 */
|
18430 |
|
18431 | new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
|
18432 | new Config(8, 16, 32, 32, deflate_slow), /* 5 */
|
18433 | new Config(8, 16, 128, 128, deflate_slow), /* 6 */
|
18434 | new Config(8, 32, 128, 256, deflate_slow), /* 7 */
|
18435 | new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
|
18436 | new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
|
18437 | ];
|
18438 |
|
18439 |
|
18440 | /* ===========================================================================
|
18441 | * Initialize the "longest match" routines for a new zlib stream
|
18442 | */
|
18443 | function lm_init(s) {
|
18444 | s.window_size = 2 * s.w_size;
|
18445 |
|
18446 | /*** CLEAR_HASH(s); ***/
|
18447 | zero(s.head); // Fill with NIL (= 0);
|
18448 |
|
18449 | /* Set the default configuration parameters:
|
18450 | */
|
18451 | s.max_lazy_match = configuration_table[s.level].max_lazy;
|
18452 | s.good_match = configuration_table[s.level].good_length;
|
18453 | s.nice_match = configuration_table[s.level].nice_length;
|
18454 | s.max_chain_length = configuration_table[s.level].max_chain;
|
18455 |
|
18456 | s.strstart = 0;
|
18457 | s.block_start = 0;
|
18458 | s.lookahead = 0;
|
18459 | s.insert = 0;
|
18460 | s.match_length = s.prev_length = MIN_MATCH - 1;
|
18461 | s.match_available = 0;
|
18462 | s.ins_h = 0;
|
18463 | }
|
18464 |
|
18465 |
|
18466 | function DeflateState() {
|
18467 | this.strm = null; /* pointer back to this zlib stream */
|
18468 | this.status = 0; /* as the name implies */
|
18469 | this.pending_buf = null; /* output still pending */
|
18470 | this.pending_buf_size = 0; /* size of pending_buf */
|
18471 | this.pending_out = 0; /* next pending byte to output to the stream */
|
18472 | this.pending = 0; /* nb of bytes in the pending buffer */
|
18473 | this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
|
18474 | this.gzhead = null; /* gzip header information to write */
|
18475 | this.gzindex = 0; /* where in extra, name, or comment */
|
18476 | this.method = Z_DEFLATED; /* can only be DEFLATED */
|
18477 | this.last_flush = -1; /* value of flush param for previous deflate call */
|
18478 |
|
18479 | this.w_size = 0; /* LZ77 window size (32K by default) */
|
18480 | this.w_bits = 0; /* log2(w_size) (8..16) */
|
18481 | this.w_mask = 0; /* w_size - 1 */
|
18482 |
|
18483 | this.window = null;
|
18484 | /* Sliding window. Input bytes are read into the second half of the window,
|
18485 | * and move to the first half later to keep a dictionary of at least wSize
|
18486 | * bytes. With this organization, matches are limited to a distance of
|
18487 | * wSize-MAX_MATCH bytes, but this ensures that IO is always
|
18488 | * performed with a length multiple of the block size.
|
18489 | */
|
18490 |
|
18491 | this.window_size = 0;
|
18492 | /* Actual size of window: 2*wSize, except when the user input buffer
|
18493 | * is directly used as sliding window.
|
18494 | */
|
18495 |
|
18496 | this.prev = null;
|
18497 | /* Link to older string with same hash index. To limit the size of this
|
18498 | * array to 64K, this link is maintained only for the last 32K strings.
|
18499 | * An index in this array is thus a window index modulo 32K.
|
18500 | */
|
18501 |
|
18502 | this.head = null; /* Heads of the hash chains or NIL. */
|
18503 |
|
18504 | this.ins_h = 0; /* hash index of string to be inserted */
|
18505 | this.hash_size = 0; /* number of elements in hash table */
|
18506 | this.hash_bits = 0; /* log2(hash_size) */
|
18507 | this.hash_mask = 0; /* hash_size-1 */
|
18508 |
|
18509 | this.hash_shift = 0;
|
18510 | /* Number of bits by which ins_h must be shifted at each input
|
18511 | * step. It must be such that after MIN_MATCH steps, the oldest
|
18512 | * byte no longer takes part in the hash key, that is:
|
18513 | * hash_shift * MIN_MATCH >= hash_bits
|
18514 | */
|
18515 |
|
18516 | this.block_start = 0;
|
18517 | /* Window position at the beginning of the current output block. Gets
|
18518 | * negative when the window is moved backwards.
|
18519 | */
|
18520 |
|
18521 | this.match_length = 0; /* length of best match */
|
18522 | this.prev_match = 0; /* previous match */
|
18523 | this.match_available = 0; /* set if previous match exists */
|
18524 | this.strstart = 0; /* start of string to insert */
|
18525 | this.match_start = 0; /* start of matching string */
|
18526 | this.lookahead = 0; /* number of valid bytes ahead in window */
|
18527 |
|
18528 | this.prev_length = 0;
|
18529 | /* Length of the best match at previous step. Matches not greater than this
|
18530 | * are discarded. This is used in the lazy match evaluation.
|
18531 | */
|
18532 |
|
18533 | this.max_chain_length = 0;
|
18534 | /* To speed up deflation, hash chains are never searched beyond this
|
18535 | * length. A higher limit improves compression ratio but degrades the
|
18536 | * speed.
|
18537 | */
|
18538 |
|
18539 | this.max_lazy_match = 0;
|
18540 | /* Attempt to find a better match only when the current match is strictly
|
18541 | * smaller than this value. This mechanism is used only for compression
|
18542 | * levels >= 4.
|
18543 | */
|
18544 | // That's alias to max_lazy_match, don't use directly
|
18545 | //this.max_insert_length = 0;
|
18546 | /* Insert new strings in the hash table only if the match length is not
|
18547 | * greater than this length. This saves time but degrades compression.
|
18548 | * max_insert_length is used only for compression levels <= 3.
|
18549 | */
|
18550 |
|
18551 | this.level = 0; /* compression level (1..9) */
|
18552 | this.strategy = 0; /* favor or force Huffman coding*/
|
18553 |
|
18554 | this.good_match = 0;
|
18555 | /* Use a faster search when the previous match is longer than this */
|
18556 |
|
18557 | this.nice_match = 0; /* Stop searching when current match exceeds this */
|
18558 |
|
18559 | /* used by trees.c: */
|
18560 |
|
18561 | /* Didn't use ct_data typedef below to suppress compiler warning */
|
18562 |
|
18563 | // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
|
18564 | // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
|
18565 | // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
|
18566 |
|
18567 | // Use flat array of DOUBLE size, with interleaved fata,
|
18568 | // because JS does not support effective
|
18569 | this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
|
18570 | this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
|
18571 | this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
|
18572 | zero(this.dyn_ltree);
|
18573 | zero(this.dyn_dtree);
|
18574 | zero(this.bl_tree);
|
18575 |
|
18576 | this.l_desc = null; /* desc. for literal tree */
|
18577 | this.d_desc = null; /* desc. for distance tree */
|
18578 | this.bl_desc = null; /* desc. for bit length tree */
|
18579 |
|
18580 | //ush bl_count[MAX_BITS+1];
|
18581 | this.bl_count = new utils.Buf16(MAX_BITS+1);
|
18582 | /* number of codes at each bit length for an optimal tree */
|
18583 |
|
18584 | //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
|
18585 | this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
|
18586 | zero(this.heap);
|
18587 |
|
18588 | this.heap_len = 0; /* number of elements in the heap */
|
18589 | this.heap_max = 0; /* element of largest frequency */
|
18590 | /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
|
18591 | * The same heap array is used to build all trees.
|
18592 | */
|
18593 |
|
18594 | this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
|
18595 | zero(this.depth);
|
18596 | /* Depth of each subtree used as tie breaker for trees of equal frequency
|
18597 | */
|
18598 |
|
18599 | this.l_buf = 0; /* buffer index for literals or lengths */
|
18600 |
|
18601 | this.lit_bufsize = 0;
|
18602 | /* Size of match buffer for literals/lengths. There are 4 reasons for
|
18603 | * limiting lit_bufsize to 64K:
|
18604 | * - frequencies can be kept in 16 bit counters
|
18605 | * - if compression is not successful for the first block, all input
|
18606 | * data is still in the window so we can still emit a stored block even
|
18607 | * when input comes from standard input. (This can also be done for
|
18608 | * all blocks if lit_bufsize is not greater than 32K.)
|
18609 | * - if compression is not successful for a file smaller than 64K, we can
|
18610 | * even emit a stored file instead of a stored block (saving 5 bytes).
|
18611 | * This is applicable only for zip (not gzip or zlib).
|
18612 | * - creating new Huffman trees less frequently may not provide fast
|
18613 | * adaptation to changes in the input data statistics. (Take for
|
18614 | * example a binary file with poorly compressible code followed by
|
18615 | * a highly compressible string table.) Smaller buffer sizes give
|
18616 | * fast adaptation but have of course the overhead of transmitting
|
18617 | * trees more frequently.
|
18618 | * - I can't count above 4
|
18619 | */
|
18620 |
|
18621 | this.last_lit = 0; /* running index in l_buf */
|
18622 |
|
18623 | this.d_buf = 0;
|
18624 | /* Buffer index for distances. To simplify the code, d_buf and l_buf have
|
18625 | * the same number of elements. To use different lengths, an extra flag
|
18626 | * array would be necessary.
|
18627 | */
|
18628 |
|
18629 | this.opt_len = 0; /* bit length of current block with optimal trees */
|
18630 | this.static_len = 0; /* bit length of current block with static trees */
|
18631 | this.matches = 0; /* number of string matches in current block */
|
18632 | this.insert = 0; /* bytes at end of window left to insert */
|
18633 |
|
18634 |
|
18635 | this.bi_buf = 0;
|
18636 | /* Output buffer. bits are inserted starting at the bottom (least
|
18637 | * significant bits).
|
18638 | */
|
18639 | this.bi_valid = 0;
|
18640 | /* Number of valid bits in bi_buf. All bits above the last valid bit
|
18641 | * are always zero.
|
18642 | */
|
18643 |
|
18644 | // Used for window memory init. We safely ignore it for JS. That makes
|
18645 | // sense only for pointers and memory check tools.
|
18646 | //this.high_water = 0;
|
18647 | /* High water mark offset in window for initialized bytes -- bytes above
|
18648 | * this are set to zero in order to avoid memory check warnings when
|
18649 | * longest match routines access bytes past the input. This is then
|
18650 | * updated to the new high water mark.
|
18651 | */
|
18652 | }
|
18653 |
|
18654 |
|
18655 | function deflateResetKeep(strm) {
|
18656 | var s;
|
18657 |
|
18658 | if (!strm || !strm.state) {
|
18659 | return err(strm, Z_STREAM_ERROR);
|
18660 | }
|
18661 |
|
18662 | strm.total_in = strm.total_out = 0;
|
18663 | strm.data_type = Z_UNKNOWN;
|
18664 |
|
18665 | s = strm.state;
|
18666 | s.pending = 0;
|
18667 | s.pending_out = 0;
|
18668 |
|
18669 | if (s.wrap < 0) {
|
18670 | s.wrap = -s.wrap;
|
18671 | /* was made negative by deflate(..., Z_FINISH); */
|
18672 | }
|
18673 | s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
|
18674 | strm.adler = (s.wrap === 2) ?
|
18675 | 0 // crc32(0, Z_NULL, 0)
|
18676 | :
|
18677 | 1; // adler32(0, Z_NULL, 0)
|
18678 | s.last_flush = Z_NO_FLUSH;
|
18679 | trees._tr_init(s);
|
18680 | return Z_OK;
|
18681 | }
|
18682 |
|
18683 |
|
18684 | function deflateReset(strm) {
|
18685 | var ret = deflateResetKeep(strm);
|
18686 | if (ret === Z_OK) {
|
18687 | lm_init(strm.state);
|
18688 | }
|
18689 | return ret;
|
18690 | }
|
18691 |
|
18692 |
|
18693 | function deflateSetHeader(strm, head) {
|
18694 | if (!strm || !strm.state) { return Z_STREAM_ERROR; }
|
18695 | if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
|
18696 | strm.state.gzhead = head;
|
18697 | return Z_OK;
|
18698 | }
|
18699 |
|
18700 |
|
18701 | function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
|
18702 | if (!strm) { // === Z_NULL
|
18703 | return Z_STREAM_ERROR;
|
18704 | }
|
18705 | var wrap = 1;
|
18706 |
|
18707 | if (level === Z_DEFAULT_COMPRESSION) {
|
18708 | level = 6;
|
18709 | }
|
18710 |
|
18711 | if (windowBits < 0) { /* suppress zlib wrapper */
|
18712 | wrap = 0;
|
18713 | windowBits = -windowBits;
|
18714 | }
|
18715 |
|
18716 | else if (windowBits > 15) {
|
18717 | wrap = 2; /* write gzip wrapper instead */
|
18718 | windowBits -= 16;
|
18719 | }
|
18720 |
|
18721 |
|
18722 | if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
|
18723 | windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
|
18724 | strategy < 0 || strategy > Z_FIXED) {
|
18725 | return err(strm, Z_STREAM_ERROR);
|
18726 | }
|
18727 |
|
18728 |
|
18729 | if (windowBits === 8) {
|
18730 | windowBits = 9;
|
18731 | }
|
18732 | /* until 256-byte window bug fixed */
|
18733 |
|
18734 | var s = new DeflateState();
|
18735 |
|
18736 | strm.state = s;
|
18737 | s.strm = strm;
|
18738 |
|
18739 | s.wrap = wrap;
|
18740 | s.gzhead = null;
|
18741 | s.w_bits = windowBits;
|
18742 | s.w_size = 1 << s.w_bits;
|
18743 | s.w_mask = s.w_size - 1;
|
18744 |
|
18745 | s.hash_bits = memLevel + 7;
|
18746 | s.hash_size = 1 << s.hash_bits;
|
18747 | s.hash_mask = s.hash_size - 1;
|
18748 | s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
|
18749 |
|
18750 | s.window = new utils.Buf8(s.w_size * 2);
|
18751 | s.head = new utils.Buf16(s.hash_size);
|
18752 | s.prev = new utils.Buf16(s.w_size);
|
18753 |
|
18754 | // Don't need mem init magic for JS.
|
18755 | //s.high_water = 0; /* nothing written to s->window yet */
|
18756 |
|
18757 | s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
|
18758 |
|
18759 | s.pending_buf_size = s.lit_bufsize * 4;
|
18760 | s.pending_buf = new utils.Buf8(s.pending_buf_size);
|
18761 |
|
18762 | s.d_buf = s.lit_bufsize >> 1;
|
18763 | s.l_buf = (1 + 2) * s.lit_bufsize;
|
18764 |
|
18765 | s.level = level;
|
18766 | s.strategy = strategy;
|
18767 | s.method = method;
|
18768 |
|
18769 | return deflateReset(strm);
|
18770 | }
|
18771 |
|
18772 | function deflateInit(strm, level) {
|
18773 | return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
|
18774 | }
|
18775 |
|
18776 |
|
18777 | function deflate(strm, flush) {
|
18778 | var old_flush, s;
|
18779 | var beg, val; // for gzip header write only
|
18780 |
|
18781 | if (!strm || !strm.state ||
|
18782 | flush > Z_BLOCK || flush < 0) {
|
18783 | return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
|
18784 | }
|
18785 |
|
18786 | s = strm.state;
|
18787 |
|
18788 | if (!strm.output ||
|
18789 | (!strm.input && strm.avail_in !== 0) ||
|
18790 | (s.status === FINISH_STATE && flush !== Z_FINISH)) {
|
18791 | return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
|
18792 | }
|
18793 |
|
18794 | s.strm = strm; /* just in case */
|
18795 | old_flush = s.last_flush;
|
18796 | s.last_flush = flush;
|
18797 |
|
18798 | /* Write the header */
|
18799 | if (s.status === INIT_STATE) {
|
18800 |
|
18801 | if (s.wrap === 2) { // GZIP header
|
18802 | strm.adler = 0; //crc32(0L, Z_NULL, 0);
|
18803 | put_byte(s, 31);
|
18804 | put_byte(s, 139);
|
18805 | put_byte(s, 8);
|
18806 | if (!s.gzhead) { // s->gzhead == Z_NULL
|
18807 | put_byte(s, 0);
|
18808 | put_byte(s, 0);
|
18809 | put_byte(s, 0);
|
18810 | put_byte(s, 0);
|
18811 | put_byte(s, 0);
|
18812 | put_byte(s, s.level === 9 ? 2 :
|
18813 | (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
|
18814 | 4 : 0));
|
18815 | put_byte(s, OS_CODE);
|
18816 | s.status = BUSY_STATE;
|
18817 | }
|
18818 | else {
|
18819 | put_byte(s, (s.gzhead.text ? 1 : 0) +
|
18820 | (s.gzhead.hcrc ? 2 : 0) +
|
18821 | (!s.gzhead.extra ? 0 : 4) +
|
18822 | (!s.gzhead.name ? 0 : 8) +
|
18823 | (!s.gzhead.comment ? 0 : 16)
|
18824 | );
|
18825 | put_byte(s, s.gzhead.time & 0xff);
|
18826 | put_byte(s, (s.gzhead.time >> 8) & 0xff);
|
18827 | put_byte(s, (s.gzhead.time >> 16) & 0xff);
|
18828 | put_byte(s, (s.gzhead.time >> 24) & 0xff);
|
18829 | put_byte(s, s.level === 9 ? 2 :
|
18830 | (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
|
18831 | 4 : 0));
|
18832 | put_byte(s, s.gzhead.os & 0xff);
|
18833 | if (s.gzhead.extra && s.gzhead.extra.length) {
|
18834 | put_byte(s, s.gzhead.extra.length & 0xff);
|
18835 | put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
|
18836 | }
|
18837 | if (s.gzhead.hcrc) {
|
18838 | strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
|
18839 | }
|
18840 | s.gzindex = 0;
|
18841 | s.status = EXTRA_STATE;
|
18842 | }
|
18843 | }
|
18844 | else // DEFLATE header
|
18845 | {
|
18846 | var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
|
18847 | var level_flags = -1;
|
18848 |
|
18849 | if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
|
18850 | level_flags = 0;
|
18851 | } else if (s.level < 6) {
|
18852 | level_flags = 1;
|
18853 | } else if (s.level === 6) {
|
18854 | level_flags = 2;
|
18855 | } else {
|
18856 | level_flags = 3;
|
18857 | }
|
18858 | header |= (level_flags << 6);
|
18859 | if (s.strstart !== 0) { header |= PRESET_DICT; }
|
18860 | header += 31 - (header % 31);
|
18861 |
|
18862 | s.status = BUSY_STATE;
|
18863 | putShortMSB(s, header);
|
18864 |
|
18865 | /* Save the adler32 of the preset dictionary: */
|
18866 | if (s.strstart !== 0) {
|
18867 | putShortMSB(s, strm.adler >>> 16);
|
18868 | putShortMSB(s, strm.adler & 0xffff);
|
18869 | }
|
18870 | strm.adler = 1; // adler32(0L, Z_NULL, 0);
|
18871 | }
|
18872 | }
|
18873 |
|
18874 | //#ifdef GZIP
|
18875 | if (s.status === EXTRA_STATE) {
|
18876 | if (s.gzhead.extra/* != Z_NULL*/) {
|
18877 | beg = s.pending; /* start of bytes to update crc */
|
18878 |
|
18879 | while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
|
18880 | if (s.pending === s.pending_buf_size) {
|
18881 | if (s.gzhead.hcrc && s.pending > beg) {
|
18882 | strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
|
18883 | }
|
18884 | flush_pending(strm);
|
18885 | beg = s.pending;
|
18886 | if (s.pending === s.pending_buf_size) {
|
18887 | break;
|
18888 | }
|
18889 | }
|
18890 | put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
|
18891 | s.gzindex++;
|
18892 | }
|
18893 | if (s.gzhead.hcrc && s.pending > beg) {
|
18894 | strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
|
18895 | }
|
18896 | if (s.gzindex === s.gzhead.extra.length) {
|
18897 | s.gzindex = 0;
|
18898 | s.status = NAME_STATE;
|
18899 | }
|
18900 | }
|
18901 | else {
|
18902 | s.status = NAME_STATE;
|
18903 | }
|
18904 | }
|
18905 | if (s.status === NAME_STATE) {
|
18906 | if (s.gzhead.name/* != Z_NULL*/) {
|
18907 | beg = s.pending; /* start of bytes to update crc */
|
18908 | //int val;
|
18909 |
|
18910 | do {
|
18911 | if (s.pending === s.pending_buf_size) {
|
18912 | if (s.gzhead.hcrc && s.pending > beg) {
|
18913 | strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
|
18914 | }
|
18915 | flush_pending(strm);
|
18916 | beg = s.pending;
|
18917 | if (s.pending === s.pending_buf_size) {
|
18918 | val = 1;
|
18919 | break;
|
18920 | }
|
18921 | }
|
18922 | // JS specific: little magic to add zero terminator to end of string
|
18923 | if (s.gzindex < s.gzhead.name.length) {
|
18924 | val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
|
18925 | } else {
|
18926 | val = 0;
|
18927 | }
|
18928 | put_byte(s, val);
|
18929 | } while (val !== 0);
|
18930 |
|
18931 | if (s.gzhead.hcrc && s.pending > beg) {
|
18932 | strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
|
18933 | }
|
18934 | if (val === 0) {
|
18935 | s.gzindex = 0;
|
18936 | s.status = COMMENT_STATE;
|
18937 | }
|
18938 | }
|
18939 | else {
|
18940 | s.status = COMMENT_STATE;
|
18941 | }
|
18942 | }
|
18943 | if (s.status === COMMENT_STATE) {
|
18944 | if (s.gzhead.comment/* != Z_NULL*/) {
|
18945 | beg = s.pending; /* start of bytes to update crc */
|
18946 | //int val;
|
18947 |
|
18948 | do {
|
18949 | if (s.pending === s.pending_buf_size) {
|
18950 | if (s.gzhead.hcrc && s.pending > beg) {
|
18951 | strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
|
18952 | }
|
18953 | flush_pending(strm);
|
18954 | beg = s.pending;
|
18955 | if (s.pending === s.pending_buf_size) {
|
18956 | val = 1;
|
18957 | break;
|
18958 | }
|
18959 | }
|
18960 | // JS specific: little magic to add zero terminator to end of string
|
18961 | if (s.gzindex < s.gzhead.comment.length) {
|
18962 | val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
|
18963 | } else {
|
18964 | val = 0;
|
18965 | }
|
18966 | put_byte(s, val);
|
18967 | } while (val !== 0);
|
18968 |
|
18969 | if (s.gzhead.hcrc && s.pending > beg) {
|
18970 | strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
|
18971 | }
|
18972 | if (val === 0) {
|
18973 | s.status = HCRC_STATE;
|
18974 | }
|
18975 | }
|
18976 | else {
|
18977 | s.status = HCRC_STATE;
|
18978 | }
|
18979 | }
|
18980 | if (s.status === HCRC_STATE) {
|
18981 | if (s.gzhead.hcrc) {
|
18982 | if (s.pending + 2 > s.pending_buf_size) {
|
18983 | flush_pending(strm);
|
18984 | }
|
18985 | if (s.pending + 2 <= s.pending_buf_size) {
|
18986 | put_byte(s, strm.adler & 0xff);
|
18987 | put_byte(s, (strm.adler >> 8) & 0xff);
|
18988 | strm.adler = 0; //crc32(0L, Z_NULL, 0);
|
18989 | s.status = BUSY_STATE;
|
18990 | }
|
18991 | }
|
18992 | else {
|
18993 | s.status = BUSY_STATE;
|
18994 | }
|
18995 | }
|
18996 | //#endif
|
18997 |
|
18998 | /* Flush as much pending output as possible */
|
18999 | if (s.pending !== 0) {
|
19000 | flush_pending(strm);
|
19001 | if (strm.avail_out === 0) {
|
19002 | /* Since avail_out is 0, deflate will be called again with
|
19003 | * more output space, but possibly with both pending and
|
19004 | * avail_in equal to zero. There won't be anything to do,
|
19005 | * but this is not an error situation so make sure we
|
19006 | * return OK instead of BUF_ERROR at next call of deflate:
|
19007 | */
|
19008 | s.last_flush = -1;
|
19009 | return Z_OK;
|
19010 | }
|
19011 |
|
19012 | /* Make sure there is something to do and avoid duplicate consecutive
|
19013 | * flushes. For repeated and useless calls with Z_FINISH, we keep
|
19014 | * returning Z_STREAM_END instead of Z_BUF_ERROR.
|
19015 | */
|
19016 | } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
|
19017 | flush !== Z_FINISH) {
|
19018 | return err(strm, Z_BUF_ERROR);
|
19019 | }
|
19020 |
|
19021 | /* User must not provide more input after the first FINISH: */
|
19022 | if (s.status === FINISH_STATE && strm.avail_in !== 0) {
|
19023 | return err(strm, Z_BUF_ERROR);
|
19024 | }
|
19025 |
|
19026 | /* Start a new block or continue the current one.
|
19027 | */
|
19028 | if (strm.avail_in !== 0 || s.lookahead !== 0 ||
|
19029 | (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
|
19030 | var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
|
19031 | (s.strategy === Z_RLE ? deflate_rle(s, flush) :
|
19032 | configuration_table[s.level].func(s, flush));
|
19033 |
|
19034 | if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
|
19035 | s.status = FINISH_STATE;
|
19036 | }
|
19037 | if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
|
19038 | if (strm.avail_out === 0) {
|
19039 | s.last_flush = -1;
|
19040 | /* avoid BUF_ERROR next call, see above */
|
19041 | }
|
19042 | return Z_OK;
|
19043 | /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
|
19044 | * of deflate should use the same flush parameter to make sure
|
19045 | * that the flush is complete. So we don't have to output an
|
19046 | * empty block here, this will be done at next call. This also
|
19047 | * ensures that for a very small output buffer, we emit at most
|
19048 | * one empty block.
|
19049 | */
|
19050 | }
|
19051 | if (bstate === BS_BLOCK_DONE) {
|
19052 | if (flush === Z_PARTIAL_FLUSH) {
|
19053 | trees._tr_align(s);
|
19054 | }
|
19055 | else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
|
19056 |
|
19057 | trees._tr_stored_block(s, 0, 0, false);
|
19058 | /* For a full flush, this empty block will be recognized
|
19059 | * as a special marker by inflate_sync().
|
19060 | */
|
19061 | if (flush === Z_FULL_FLUSH) {
|
19062 | /*** CLEAR_HASH(s); ***/ /* forget history */
|
19063 | zero(s.head); // Fill with NIL (= 0);
|
19064 |
|
19065 | if (s.lookahead === 0) {
|
19066 | s.strstart = 0;
|
19067 | s.block_start = 0;
|
19068 | s.insert = 0;
|
19069 | }
|
19070 | }
|
19071 | }
|
19072 | flush_pending(strm);
|
19073 | if (strm.avail_out === 0) {
|
19074 | s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
|
19075 | return Z_OK;
|
19076 | }
|
19077 | }
|
19078 | }
|
19079 | //Assert(strm->avail_out > 0, "bug2");
|
19080 | //if (strm.avail_out <= 0) { throw new Error("bug2");}
|
19081 |
|
19082 | if (flush !== Z_FINISH) { return Z_OK; }
|
19083 | if (s.wrap <= 0) { return Z_STREAM_END; }
|
19084 |
|
19085 | /* Write the trailer */
|
19086 | if (s.wrap === 2) {
|
19087 | put_byte(s, strm.adler & 0xff);
|
19088 | put_byte(s, (strm.adler >> 8) & 0xff);
|
19089 | put_byte(s, (strm.adler >> 16) & 0xff);
|
19090 | put_byte(s, (strm.adler >> 24) & 0xff);
|
19091 | put_byte(s, strm.total_in & 0xff);
|
19092 | put_byte(s, (strm.total_in >> 8) & 0xff);
|
19093 | put_byte(s, (strm.total_in >> 16) & 0xff);
|
19094 | put_byte(s, (strm.total_in >> 24) & 0xff);
|
19095 | }
|
19096 | else
|
19097 | {
|
19098 | putShortMSB(s, strm.adler >>> 16);
|
19099 | putShortMSB(s, strm.adler & 0xffff);
|
19100 | }
|
19101 |
|
19102 | flush_pending(strm);
|
19103 | /* If avail_out is zero, the application will call deflate again
|
19104 | * to flush the rest.
|
19105 | */
|
19106 | if (s.wrap > 0) { s.wrap = -s.wrap; }
|
19107 | /* write the trailer only once! */
|
19108 | return s.pending !== 0 ? Z_OK : Z_STREAM_END;
|
19109 | }
|
19110 |
|
19111 | function deflateEnd(strm) {
|
19112 | var status;
|
19113 |
|
19114 | if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
|
19115 | return Z_STREAM_ERROR;
|
19116 | }
|
19117 |
|
19118 | status = strm.state.status;
|
19119 | if (status !== INIT_STATE &&
|
19120 | status !== EXTRA_STATE &&
|
19121 | status !== NAME_STATE &&
|
19122 | status !== COMMENT_STATE &&
|
19123 | status !== HCRC_STATE &&
|
19124 | status !== BUSY_STATE &&
|
19125 | status !== FINISH_STATE
|
19126 | ) {
|
19127 | return err(strm, Z_STREAM_ERROR);
|
19128 | }
|
19129 |
|
19130 | strm.state = null;
|
19131 |
|
19132 | return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
|
19133 | }
|
19134 |
|
19135 | /* =========================================================================
|
19136 | * Copy the source state to the destination state
|
19137 | */
|
19138 | //function deflateCopy(dest, source) {
|
19139 | //
|
19140 | //}
|
19141 |
|
19142 | exports.deflateInit = deflateInit;
|
19143 | exports.deflateInit2 = deflateInit2;
|
19144 | exports.deflateReset = deflateReset;
|
19145 | exports.deflateResetKeep = deflateResetKeep;
|
19146 | exports.deflateSetHeader = deflateSetHeader;
|
19147 | exports.deflate = deflate;
|
19148 | exports.deflateEnd = deflateEnd;
|
19149 | exports.deflateInfo = 'pako deflate (from Nodeca project)';
|
19150 |
|
19151 | /* Not implemented
|
19152 | exports.deflateBound = deflateBound;
|
19153 | exports.deflateCopy = deflateCopy;
|
19154 | exports.deflateSetDictionary = deflateSetDictionary;
|
19155 | exports.deflateParams = deflateParams;
|
19156 | exports.deflatePending = deflatePending;
|
19157 | exports.deflatePrime = deflatePrime;
|
19158 | exports.deflateTune = deflateTune;
|
19159 | */
|
19160 |
|
19161 | },{"../utils/common":14,"./adler32":16,"./crc32":18,"./messages":24,"./trees":25}],20:[function(require,module,exports){
|
19162 | 'use strict';
|
19163 |
|
19164 |
|
19165 | function GZheader() {
|
19166 | /* true if compressed data believed to be text */
|
19167 | this.text = 0;
|
19168 | /* modification time */
|
19169 | this.time = 0;
|
19170 | /* extra flags (not used when writing a gzip file) */
|
19171 | this.xflags = 0;
|
19172 | /* operating system */
|
19173 | this.os = 0;
|
19174 | /* pointer to extra field or Z_NULL if none */
|
19175 | this.extra = null;
|
19176 | /* extra field length (valid if extra != Z_NULL) */
|
19177 | this.extra_len = 0; // Actually, we don't need it in JS,
|
19178 | // but leave for few code modifications
|
19179 |
|
19180 | //
|
19181 | // Setup limits is not necessary because in js we should not preallocate memory
|
19182 | // for inflate use constant limit in 65536 bytes
|
19183 | //
|
19184 |
|
19185 | /* space at extra (only when reading header) */
|
19186 | // this.extra_max = 0;
|
19187 | /* pointer to zero-terminated file name or Z_NULL */
|
19188 | this.name = '';
|
19189 | /* space at name (only when reading header) */
|
19190 | // this.name_max = 0;
|
19191 | /* pointer to zero-terminated comment or Z_NULL */
|
19192 | this.comment = '';
|
19193 | /* space at comment (only when reading header) */
|
19194 | // this.comm_max = 0;
|
19195 | /* true if there was or will be a header crc */
|
19196 | this.hcrc = 0;
|
19197 | /* true when done reading gzip header (not used when writing a gzip file) */
|
19198 | this.done = false;
|
19199 | }
|
19200 |
|
19201 | module.exports = GZheader;
|
19202 |
|
19203 | },{}],21:[function(require,module,exports){
|
19204 | 'use strict';
|
19205 |
|
19206 | // See state defs from inflate.js
|
19207 | var BAD = 30; /* got a data error -- remain here until reset */
|
19208 | var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
|
19209 |
|
19210 | /*
|
19211 | Decode literal, length, and distance codes and write out the resulting
|
19212 | literal and match bytes until either not enough input or output is
|
19213 | available, an end-of-block is encountered, or a data error is encountered.
|
19214 | When large enough input and output buffers are supplied to inflate(), for
|
19215 | example, a 16K input buffer and a 64K output buffer, more than 95% of the
|
19216 | inflate execution time is spent in this routine.
|
19217 |
|
19218 | Entry assumptions:
|
19219 |
|
19220 | state.mode === LEN
|
19221 | strm.avail_in >= 6
|
19222 | strm.avail_out >= 258
|
19223 | start >= strm.avail_out
|
19224 | state.bits < 8
|
19225 |
|
19226 | On return, state.mode is one of:
|
19227 |
|
19228 | LEN -- ran out of enough output space or enough available input
|
19229 | TYPE -- reached end of block code, inflate() to interpret next block
|
19230 | BAD -- error in block data
|
19231 |
|
19232 | Notes:
|
19233 |
|
19234 | - The maximum input bits used by a length/distance pair is 15 bits for the
|
19235 | length code, 5 bits for the length extra, 15 bits for the distance code,
|
19236 | and 13 bits for the distance extra. This totals 48 bits, or six bytes.
|
19237 | Therefore if strm.avail_in >= 6, then there is enough input to avoid
|
19238 | checking for available input while decoding.
|
19239 |
|
19240 | - The maximum bytes that a single length/distance pair can output is 258
|
19241 | bytes, which is the maximum length that can be coded. inflate_fast()
|
19242 | requires strm.avail_out >= 258 for each loop to avoid checking for
|
19243 | output space.
|
19244 | */
|
19245 | module.exports = function inflate_fast(strm, start) {
|
19246 | var state;
|
19247 | var _in; /* local strm.input */
|
19248 | var last; /* have enough input while in < last */
|
19249 | var _out; /* local strm.output */
|
19250 | var beg; /* inflate()'s initial strm.output */
|
19251 | var end; /* while out < end, enough space available */
|
19252 | //#ifdef INFLATE_STRICT
|
19253 | var dmax; /* maximum distance from zlib header */
|
19254 | //#endif
|
19255 | var wsize; /* window size or zero if not using window */
|
19256 | var whave; /* valid bytes in the window */
|
19257 | var wnext; /* window write index */
|
19258 | var window; /* allocated sliding window, if wsize != 0 */
|
19259 | var hold; /* local strm.hold */
|
19260 | var bits; /* local strm.bits */
|
19261 | var lcode; /* local strm.lencode */
|
19262 | var dcode; /* local strm.distcode */
|
19263 | var lmask; /* mask for first level of length codes */
|
19264 | var dmask; /* mask for first level of distance codes */
|
19265 | var here; /* retrieved table entry */
|
19266 | var op; /* code bits, operation, extra bits, or */
|
19267 | /* window position, window bytes to copy */
|
19268 | var len; /* match length, unused bytes */
|
19269 | var dist; /* match distance */
|
19270 | var from; /* where to copy match from */
|
19271 | var from_source;
|
19272 |
|
19273 |
|
19274 | var input, output; // JS specific, because we have no pointers
|
19275 |
|
19276 | /* copy state to local variables */
|
19277 | state = strm.state;
|
19278 | //here = state.here;
|
19279 | _in = strm.next_in;
|
19280 | input = strm.input;
|
19281 | last = _in + (strm.avail_in - 5);
|
19282 | _out = strm.next_out;
|
19283 | output = strm.output;
|
19284 | beg = _out - (start - strm.avail_out);
|
19285 | end = _out + (strm.avail_out - 257);
|
19286 | //#ifdef INFLATE_STRICT
|
19287 | dmax = state.dmax;
|
19288 | //#endif
|
19289 | wsize = state.wsize;
|
19290 | whave = state.whave;
|
19291 | wnext = state.wnext;
|
19292 | window = state.window;
|
19293 | hold = state.hold;
|
19294 | bits = state.bits;
|
19295 | lcode = state.lencode;
|
19296 | dcode = state.distcode;
|
19297 | lmask = (1 << state.lenbits) - 1;
|
19298 | dmask = (1 << state.distbits) - 1;
|
19299 |
|
19300 |
|
19301 | /* decode literals and length/distances until end-of-block or not enough
|
19302 | input data or output space */
|
19303 |
|
19304 | top:
|
19305 | do {
|
19306 | if (bits < 15) {
|
19307 | hold += input[_in++] << bits;
|
19308 | bits += 8;
|
19309 | hold += input[_in++] << bits;
|
19310 | bits += 8;
|
19311 | }
|
19312 |
|
19313 | here = lcode[hold & lmask];
|
19314 |
|
19315 | dolen:
|
19316 | for (;;) { // Goto emulation
|
19317 | op = here >>> 24/*here.bits*/;
|
19318 | hold >>>= op;
|
19319 | bits -= op;
|
19320 | op = (here >>> 16) & 0xff/*here.op*/;
|
19321 | if (op === 0) { /* literal */
|
19322 | //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
|
19323 | // "inflate: literal '%c'\n" :
|
19324 | // "inflate: literal 0x%02x\n", here.val));
|
19325 | output[_out++] = here & 0xffff/*here.val*/;
|
19326 | }
|
19327 | else if (op & 16) { /* length base */
|
19328 | len = here & 0xffff/*here.val*/;
|
19329 | op &= 15; /* number of extra bits */
|
19330 | if (op) {
|
19331 | if (bits < op) {
|
19332 | hold += input[_in++] << bits;
|
19333 | bits += 8;
|
19334 | }
|
19335 | len += hold & ((1 << op) - 1);
|
19336 | hold >>>= op;
|
19337 | bits -= op;
|
19338 | }
|
19339 | //Tracevv((stderr, "inflate: length %u\n", len));
|
19340 | if (bits < 15) {
|
19341 | hold += input[_in++] << bits;
|
19342 | bits += 8;
|
19343 | hold += input[_in++] << bits;
|
19344 | bits += 8;
|
19345 | }
|
19346 | here = dcode[hold & dmask];
|
19347 |
|
19348 | dodist:
|
19349 | for (;;) { // goto emulation
|
19350 | op = here >>> 24/*here.bits*/;
|
19351 | hold >>>= op;
|
19352 | bits -= op;
|
19353 | op = (here >>> 16) & 0xff/*here.op*/;
|
19354 |
|
19355 | if (op & 16) { /* distance base */
|
19356 | dist = here & 0xffff/*here.val*/;
|
19357 | op &= 15; /* number of extra bits */
|
19358 | if (bits < op) {
|
19359 | hold += input[_in++] << bits;
|
19360 | bits += 8;
|
19361 | if (bits < op) {
|
19362 | hold += input[_in++] << bits;
|
19363 | bits += 8;
|
19364 | }
|
19365 | }
|
19366 | dist += hold & ((1 << op) - 1);
|
19367 | //#ifdef INFLATE_STRICT
|
19368 | if (dist > dmax) {
|
19369 | strm.msg = 'invalid distance too far back';
|
19370 | state.mode = BAD;
|
19371 | break top;
|
19372 | }
|
19373 | //#endif
|
19374 | hold >>>= op;
|
19375 | bits -= op;
|
19376 | //Tracevv((stderr, "inflate: distance %u\n", dist));
|
19377 | op = _out - beg; /* max distance in output */
|
19378 | if (dist > op) { /* see if copy from window */
|
19379 | op = dist - op; /* distance back in window */
|
19380 | if (op > whave) {
|
19381 | if (state.sane) {
|
19382 | strm.msg = 'invalid distance too far back';
|
19383 | state.mode = BAD;
|
19384 | break top;
|
19385 | }
|
19386 |
|
19387 | // (!) This block is disabled in zlib defailts,
|
19388 | // don't enable it for binary compatibility
|
19389 | //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
|
19390 | // if (len <= op - whave) {
|
19391 | // do {
|
19392 | // output[_out++] = 0;
|
19393 | // } while (--len);
|
19394 | // continue top;
|
19395 | // }
|
19396 | // len -= op - whave;
|
19397 | // do {
|
19398 | // output[_out++] = 0;
|
19399 | // } while (--op > whave);
|
19400 | // if (op === 0) {
|
19401 | // from = _out - dist;
|
19402 | // do {
|
19403 | // output[_out++] = output[from++];
|
19404 | // } while (--len);
|
19405 | // continue top;
|
19406 | // }
|
19407 | //#endif
|
19408 | }
|
19409 | from = 0; // window index
|
19410 | from_source = window;
|
19411 | if (wnext === 0) { /* very common case */
|
19412 | from += wsize - op;
|
19413 | if (op < len) { /* some from window */
|
19414 | len -= op;
|
19415 | do {
|
19416 | output[_out++] = window[from++];
|
19417 | } while (--op);
|
19418 | from = _out - dist; /* rest from output */
|
19419 | from_source = output;
|
19420 | }
|
19421 | }
|
19422 | else if (wnext < op) { /* wrap around window */
|
19423 | from += wsize + wnext - op;
|
19424 | op -= wnext;
|
19425 | if (op < len) { /* some from end of window */
|
19426 | len -= op;
|
19427 | do {
|
19428 | output[_out++] = window[from++];
|
19429 | } while (--op);
|
19430 | from = 0;
|
19431 | if (wnext < len) { /* some from start of window */
|
19432 | op = wnext;
|
19433 | len -= op;
|
19434 | do {
|
19435 | output[_out++] = window[from++];
|
19436 | } while (--op);
|
19437 | from = _out - dist; /* rest from output */
|
19438 | from_source = output;
|
19439 | }
|
19440 | }
|
19441 | }
|
19442 | else { /* contiguous in window */
|
19443 | from += wnext - op;
|
19444 | if (op < len) { /* some from window */
|
19445 | len -= op;
|
19446 | do {
|
19447 | output[_out++] = window[from++];
|
19448 | } while (--op);
|
19449 | from = _out - dist; /* rest from output */
|
19450 | from_source = output;
|
19451 | }
|
19452 | }
|
19453 | while (len > 2) {
|
19454 | output[_out++] = from_source[from++];
|
19455 | output[_out++] = from_source[from++];
|
19456 | output[_out++] = from_source[from++];
|
19457 | len -= 3;
|
19458 | }
|
19459 | if (len) {
|
19460 | output[_out++] = from_source[from++];
|
19461 | if (len > 1) {
|
19462 | output[_out++] = from_source[from++];
|
19463 | }
|
19464 | }
|
19465 | }
|
19466 | else {
|
19467 | from = _out - dist; /* copy direct from output */
|
19468 | do { /* minimum length is three */
|
19469 | output[_out++] = output[from++];
|
19470 | output[_out++] = output[from++];
|
19471 | output[_out++] = output[from++];
|
19472 | len -= 3;
|
19473 | } while (len > 2);
|
19474 | if (len) {
|
19475 | output[_out++] = output[from++];
|
19476 | if (len > 1) {
|
19477 | output[_out++] = output[from++];
|
19478 | }
|
19479 | }
|
19480 | }
|
19481 | }
|
19482 | else if ((op & 64) === 0) { /* 2nd level distance code */
|
19483 | here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
|
19484 | continue dodist;
|
19485 | }
|
19486 | else {
|
19487 | strm.msg = 'invalid distance code';
|
19488 | state.mode = BAD;
|
19489 | break top;
|
19490 | }
|
19491 |
|
19492 | break; // need to emulate goto via "continue"
|
19493 | }
|
19494 | }
|
19495 | else if ((op & 64) === 0) { /* 2nd level length code */
|
19496 | here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
|
19497 | continue dolen;
|
19498 | }
|
19499 | else if (op & 32) { /* end-of-block */
|
19500 | //Tracevv((stderr, "inflate: end of block\n"));
|
19501 | state.mode = TYPE;
|
19502 | break top;
|
19503 | }
|
19504 | else {
|
19505 | strm.msg = 'invalid literal/length code';
|
19506 | state.mode = BAD;
|
19507 | break top;
|
19508 | }
|
19509 |
|
19510 | break; // need to emulate goto via "continue"
|
19511 | }
|
19512 | } while (_in < last && _out < end);
|
19513 |
|
19514 | /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
|
19515 | len = bits >> 3;
|
19516 | _in -= len;
|
19517 | bits -= len << 3;
|
19518 | hold &= (1 << bits) - 1;
|
19519 |
|
19520 | /* update state and return */
|
19521 | strm.next_in = _in;
|
19522 | strm.next_out = _out;
|
19523 | strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
|
19524 | strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
|
19525 | state.hold = hold;
|
19526 | state.bits = bits;
|
19527 | return;
|
19528 | };
|
19529 |
|
19530 | },{}],22:[function(require,module,exports){
|
19531 | 'use strict';
|
19532 |
|
19533 |
|
19534 | var utils = require('../utils/common');
|
19535 | var adler32 = require('./adler32');
|
19536 | var crc32 = require('./crc32');
|
19537 | var inflate_fast = require('./inffast');
|
19538 | var inflate_table = require('./inftrees');
|
19539 |
|
19540 | var CODES = 0;
|
19541 | var LENS = 1;
|
19542 | var DISTS = 2;
|
19543 |
|
19544 | /* Public constants ==========================================================*/
|
19545 | /* ===========================================================================*/
|
19546 |
|
19547 |
|
19548 | /* Allowed flush values; see deflate() and inflate() below for details */
|
19549 | //var Z_NO_FLUSH = 0;
|
19550 | //var Z_PARTIAL_FLUSH = 1;
|
19551 | //var Z_SYNC_FLUSH = 2;
|
19552 | //var Z_FULL_FLUSH = 3;
|
19553 | var Z_FINISH = 4;
|
19554 | var Z_BLOCK = 5;
|
19555 | var Z_TREES = 6;
|
19556 |
|
19557 |
|
19558 | /* Return codes for the compression/decompression functions. Negative values
|
19559 | * are errors, positive values are used for special but normal events.
|
19560 | */
|
19561 | var Z_OK = 0;
|
19562 | var Z_STREAM_END = 1;
|
19563 | var Z_NEED_DICT = 2;
|
19564 | //var Z_ERRNO = -1;
|
19565 | var Z_STREAM_ERROR = -2;
|
19566 | var Z_DATA_ERROR = -3;
|
19567 | var Z_MEM_ERROR = -4;
|
19568 | var Z_BUF_ERROR = -5;
|
19569 | //var Z_VERSION_ERROR = -6;
|
19570 |
|
19571 | /* The deflate compression method */
|
19572 | var Z_DEFLATED = 8;
|
19573 |
|
19574 |
|
19575 | /* STATES ====================================================================*/
|
19576 | /* ===========================================================================*/
|
19577 |
|
19578 |
|
19579 | var HEAD = 1; /* i: waiting for magic header */
|
19580 | var FLAGS = 2; /* i: waiting for method and flags (gzip) */
|
19581 | var TIME = 3; /* i: waiting for modification time (gzip) */
|
19582 | var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
|
19583 | var EXLEN = 5; /* i: waiting for extra length (gzip) */
|
19584 | var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
|
19585 | var NAME = 7; /* i: waiting for end of file name (gzip) */
|
19586 | var COMMENT = 8; /* i: waiting for end of comment (gzip) */
|
19587 | var HCRC = 9; /* i: waiting for header crc (gzip) */
|
19588 | var DICTID = 10; /* i: waiting for dictionary check value */
|
19589 | var DICT = 11; /* waiting for inflateSetDictionary() call */
|
19590 | var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
|
19591 | var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
|
19592 | var STORED = 14; /* i: waiting for stored size (length and complement) */
|
19593 | var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
|
19594 | var COPY = 16; /* i/o: waiting for input or output to copy stored block */
|
19595 | var TABLE = 17; /* i: waiting for dynamic block table lengths */
|
19596 | var LENLENS = 18; /* i: waiting for code length code lengths */
|
19597 | var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
|
19598 | var LEN_ = 20; /* i: same as LEN below, but only first time in */
|
19599 | var LEN = 21; /* i: waiting for length/lit/eob code */
|
19600 | var LENEXT = 22; /* i: waiting for length extra bits */
|
19601 | var DIST = 23; /* i: waiting for distance code */
|
19602 | var DISTEXT = 24; /* i: waiting for distance extra bits */
|
19603 | var MATCH = 25; /* o: waiting for output space to copy string */
|
19604 | var LIT = 26; /* o: waiting for output space to write literal */
|
19605 | var CHECK = 27; /* i: waiting for 32-bit check value */
|
19606 | var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
|
19607 | var DONE = 29; /* finished check, done -- remain here until reset */
|
19608 | var BAD = 30; /* got a data error -- remain here until reset */
|
19609 | var MEM = 31; /* got an inflate() memory error -- remain here until reset */
|
19610 | var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
|
19611 |
|
19612 | /* ===========================================================================*/
|
19613 |
|
19614 |
|
19615 |
|
19616 | var ENOUGH_LENS = 852;
|
19617 | var ENOUGH_DISTS = 592;
|
19618 | //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
|
19619 |
|
19620 | var MAX_WBITS = 15;
|
19621 | /* 32K LZ77 window */
|
19622 | var DEF_WBITS = MAX_WBITS;
|
19623 |
|
19624 |
|
19625 | function ZSWAP32(q) {
|
19626 | return (((q >>> 24) & 0xff) +
|
19627 | ((q >>> 8) & 0xff00) +
|
19628 | ((q & 0xff00) << 8) +
|
19629 | ((q & 0xff) << 24));
|
19630 | }
|
19631 |
|
19632 |
|
19633 | function InflateState() {
|
19634 | this.mode = 0; /* current inflate mode */
|
19635 | this.last = false; /* true if processing last block */
|
19636 | this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
|
19637 | this.havedict = false; /* true if dictionary provided */
|
19638 | this.flags = 0; /* gzip header method and flags (0 if zlib) */
|
19639 | this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
|
19640 | this.check = 0; /* protected copy of check value */
|
19641 | this.total = 0; /* protected copy of output count */
|
19642 | // TODO: may be {}
|
19643 | this.head = null; /* where to save gzip header information */
|
19644 |
|
19645 | /* sliding window */
|
19646 | this.wbits = 0; /* log base 2 of requested window size */
|
19647 | this.wsize = 0; /* window size or zero if not using window */
|
19648 | this.whave = 0; /* valid bytes in the window */
|
19649 | this.wnext = 0; /* window write index */
|
19650 | this.window = null; /* allocated sliding window, if needed */
|
19651 |
|
19652 | /* bit accumulator */
|
19653 | this.hold = 0; /* input bit accumulator */
|
19654 | this.bits = 0; /* number of bits in "in" */
|
19655 |
|
19656 | /* for string and stored block copying */
|
19657 | this.length = 0; /* literal or length of data to copy */
|
19658 | this.offset = 0; /* distance back to copy string from */
|
19659 |
|
19660 | /* for table and code decoding */
|
19661 | this.extra = 0; /* extra bits needed */
|
19662 |
|
19663 | /* fixed and dynamic code tables */
|
19664 | this.lencode = null; /* starting table for length/literal codes */
|
19665 | this.distcode = null; /* starting table for distance codes */
|
19666 | this.lenbits = 0; /* index bits for lencode */
|
19667 | this.distbits = 0; /* index bits for distcode */
|
19668 |
|
19669 | /* dynamic table building */
|
19670 | this.ncode = 0; /* number of code length code lengths */
|
19671 | this.nlen = 0; /* number of length code lengths */
|
19672 | this.ndist = 0; /* number of distance code lengths */
|
19673 | this.have = 0; /* number of code lengths in lens[] */
|
19674 | this.next = null; /* next available space in codes[] */
|
19675 |
|
19676 | this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
|
19677 | this.work = new utils.Buf16(288); /* work area for code table building */
|
19678 |
|
19679 | /*
|
19680 | because we don't have pointers in js, we use lencode and distcode directly
|
19681 | as buffers so we don't need codes
|
19682 | */
|
19683 | //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
|
19684 | this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
|
19685 | this.distdyn = null; /* dynamic table for distance codes (JS specific) */
|
19686 | this.sane = 0; /* if false, allow invalid distance too far */
|
19687 | this.back = 0; /* bits back of last unprocessed length/lit */
|
19688 | this.was = 0; /* initial length of match */
|
19689 | }
|
19690 |
|
19691 | function inflateResetKeep(strm) {
|
19692 | var state;
|
19693 |
|
19694 | if (!strm || !strm.state) { return Z_STREAM_ERROR; }
|
19695 | state = strm.state;
|
19696 | strm.total_in = strm.total_out = state.total = 0;
|
19697 | strm.msg = ''; /*Z_NULL*/
|
19698 | if (state.wrap) { /* to support ill-conceived Java test suite */
|
19699 | strm.adler = state.wrap & 1;
|
19700 | }
|
19701 | state.mode = HEAD;
|
19702 | state.last = 0;
|
19703 | state.havedict = 0;
|
19704 | state.dmax = 32768;
|
19705 | state.head = null/*Z_NULL*/;
|
19706 | state.hold = 0;
|
19707 | state.bits = 0;
|
19708 | //state.lencode = state.distcode = state.next = state.codes;
|
19709 | state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
|
19710 | state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
|
19711 |
|
19712 | state.sane = 1;
|
19713 | state.back = -1;
|
19714 | //Tracev((stderr, "inflate: reset\n"));
|
19715 | return Z_OK;
|
19716 | }
|
19717 |
|
19718 | function inflateReset(strm) {
|
19719 | var state;
|
19720 |
|
19721 | if (!strm || !strm.state) { return Z_STREAM_ERROR; }
|
19722 | state = strm.state;
|
19723 | state.wsize = 0;
|
19724 | state.whave = 0;
|
19725 | state.wnext = 0;
|
19726 | return inflateResetKeep(strm);
|
19727 |
|
19728 | }
|
19729 |
|
19730 | function inflateReset2(strm, windowBits) {
|
19731 | var wrap;
|
19732 | var state;
|
19733 |
|
19734 | /* get the state */
|
19735 | if (!strm || !strm.state) { return Z_STREAM_ERROR; }
|
19736 | state = strm.state;
|
19737 |
|
19738 | /* extract wrap request from windowBits parameter */
|
19739 | if (windowBits < 0) {
|
19740 | wrap = 0;
|
19741 | windowBits = -windowBits;
|
19742 | }
|
19743 | else {
|
19744 | wrap = (windowBits >> 4) + 1;
|
19745 | if (windowBits < 48) {
|
19746 | windowBits &= 15;
|
19747 | }
|
19748 | }
|
19749 |
|
19750 | /* set number of window bits, free window if different */
|
19751 | if (windowBits && (windowBits < 8 || windowBits > 15)) {
|
19752 | return Z_STREAM_ERROR;
|
19753 | }
|
19754 | if (state.window !== null && state.wbits !== windowBits) {
|
19755 | state.window = null;
|
19756 | }
|
19757 |
|
19758 | /* update state and reset the rest of it */
|
19759 | state.wrap = wrap;
|
19760 | state.wbits = windowBits;
|
19761 | return inflateReset(strm);
|
19762 | }
|
19763 |
|
19764 | function inflateInit2(strm, windowBits) {
|
19765 | var ret;
|
19766 | var state;
|
19767 |
|
19768 | if (!strm) { return Z_STREAM_ERROR; }
|
19769 | //strm.msg = Z_NULL; /* in case we return an error */
|
19770 |
|
19771 | state = new InflateState();
|
19772 |
|
19773 | //if (state === Z_NULL) return Z_MEM_ERROR;
|
19774 | //Tracev((stderr, "inflate: allocated\n"));
|
19775 | strm.state = state;
|
19776 | state.window = null/*Z_NULL*/;
|
19777 | ret = inflateReset2(strm, windowBits);
|
19778 | if (ret !== Z_OK) {
|
19779 | strm.state = null/*Z_NULL*/;
|
19780 | }
|
19781 | return ret;
|
19782 | }
|
19783 |
|
19784 | function inflateInit(strm) {
|
19785 | return inflateInit2(strm, DEF_WBITS);
|
19786 | }
|
19787 |
|
19788 |
|
19789 | /*
|
19790 | Return state with length and distance decoding tables and index sizes set to
|
19791 | fixed code decoding. Normally this returns fixed tables from inffixed.h.
|
19792 | If BUILDFIXED is defined, then instead this routine builds the tables the
|
19793 | first time it's called, and returns those tables the first time and
|
19794 | thereafter. This reduces the size of the code by about 2K bytes, in
|
19795 | exchange for a little execution time. However, BUILDFIXED should not be
|
19796 | used for threaded applications, since the rewriting of the tables and virgin
|
19797 | may not be thread-safe.
|
19798 | */
|
19799 | var virgin = true;
|
19800 |
|
19801 | var lenfix, distfix; // We have no pointers in JS, so keep tables separate
|
19802 |
|
19803 | function fixedtables(state) {
|
19804 | /* build fixed huffman tables if first call (may not be thread safe) */
|
19805 | if (virgin) {
|
19806 | var sym;
|
19807 |
|
19808 | lenfix = new utils.Buf32(512);
|
19809 | distfix = new utils.Buf32(32);
|
19810 |
|
19811 | /* literal/length table */
|
19812 | sym = 0;
|
19813 | while (sym < 144) { state.lens[sym++] = 8; }
|
19814 | while (sym < 256) { state.lens[sym++] = 9; }
|
19815 | while (sym < 280) { state.lens[sym++] = 7; }
|
19816 | while (sym < 288) { state.lens[sym++] = 8; }
|
19817 |
|
19818 | inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
|
19819 |
|
19820 | /* distance table */
|
19821 | sym = 0;
|
19822 | while (sym < 32) { state.lens[sym++] = 5; }
|
19823 |
|
19824 | inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
|
19825 |
|
19826 | /* do this just once */
|
19827 | virgin = false;
|
19828 | }
|
19829 |
|
19830 | state.lencode = lenfix;
|
19831 | state.lenbits = 9;
|
19832 | state.distcode = distfix;
|
19833 | state.distbits = 5;
|
19834 | }
|
19835 |
|
19836 |
|
19837 | /*
|
19838 | Update the window with the last wsize (normally 32K) bytes written before
|
19839 | returning. If window does not exist yet, create it. This is only called
|
19840 | when a window is already in use, or when output has been written during this
|
19841 | inflate call, but the end of the deflate stream has not been reached yet.
|
19842 | It is also called to create a window for dictionary data when a dictionary
|
19843 | is loaded.
|
19844 |
|
19845 | Providing output buffers larger than 32K to inflate() should provide a speed
|
19846 | advantage, since only the last 32K of output is copied to the sliding window
|
19847 | upon return from inflate(), and since all distances after the first 32K of
|
19848 | output will fall in the output data, making match copies simpler and faster.
|
19849 | The advantage may be dependent on the size of the processor's data caches.
|
19850 | */
|
19851 | function updatewindow(strm, src, end, copy) {
|
19852 | var dist;
|
19853 | var state = strm.state;
|
19854 |
|
19855 | /* if it hasn't been done already, allocate space for the window */
|
19856 | if (state.window === null) {
|
19857 | state.wsize = 1 << state.wbits;
|
19858 | state.wnext = 0;
|
19859 | state.whave = 0;
|
19860 |
|
19861 | state.window = new utils.Buf8(state.wsize);
|
19862 | }
|
19863 |
|
19864 | /* copy state->wsize or less output bytes into the circular window */
|
19865 | if (copy >= state.wsize) {
|
19866 | utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
|
19867 | state.wnext = 0;
|
19868 | state.whave = state.wsize;
|
19869 | }
|
19870 | else {
|
19871 | dist = state.wsize - state.wnext;
|
19872 | if (dist > copy) {
|
19873 | dist = copy;
|
19874 | }
|
19875 | //zmemcpy(state->window + state->wnext, end - copy, dist);
|
19876 | utils.arraySet(state.window,src, end - copy, dist, state.wnext);
|
19877 | copy -= dist;
|
19878 | if (copy) {
|
19879 | //zmemcpy(state->window, end - copy, copy);
|
19880 | utils.arraySet(state.window,src, end - copy, copy, 0);
|
19881 | state.wnext = copy;
|
19882 | state.whave = state.wsize;
|
19883 | }
|
19884 | else {
|
19885 | state.wnext += dist;
|
19886 | if (state.wnext === state.wsize) { state.wnext = 0; }
|
19887 | if (state.whave < state.wsize) { state.whave += dist; }
|
19888 | }
|
19889 | }
|
19890 | return 0;
|
19891 | }
|
19892 |
|
19893 | function inflate(strm, flush) {
|
19894 | var state;
|
19895 | var input, output; // input/output buffers
|
19896 | var next; /* next input INDEX */
|
19897 | var put; /* next output INDEX */
|
19898 | var have, left; /* available input and output */
|
19899 | var hold; /* bit buffer */
|
19900 | var bits; /* bits in bit buffer */
|
19901 | var _in, _out; /* save starting available input and output */
|
19902 | var copy; /* number of stored or match bytes to copy */
|
19903 | var from; /* where to copy match bytes from */
|
19904 | var from_source;
|
19905 | var here = 0; /* current decoding table entry */
|
19906 | var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
|
19907 | //var last; /* parent table entry */
|
19908 | var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
|
19909 | var len; /* length to copy for repeats, bits to drop */
|
19910 | var ret; /* return code */
|
19911 | var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
|
19912 | var opts;
|
19913 |
|
19914 | var n; // temporary var for NEED_BITS
|
19915 |
|
19916 | var order = /* permutation of code lengths */
|
19917 | [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
|
19918 |
|
19919 |
|
19920 | if (!strm || !strm.state || !strm.output ||
|
19921 | (!strm.input && strm.avail_in !== 0)) {
|
19922 | return Z_STREAM_ERROR;
|
19923 | }
|
19924 |
|
19925 | state = strm.state;
|
19926 | if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
|
19927 |
|
19928 |
|
19929 | //--- LOAD() ---
|
19930 | put = strm.next_out;
|
19931 | output = strm.output;
|
19932 | left = strm.avail_out;
|
19933 | next = strm.next_in;
|
19934 | input = strm.input;
|
19935 | have = strm.avail_in;
|
19936 | hold = state.hold;
|
19937 | bits = state.bits;
|
19938 | //---
|
19939 |
|
19940 | _in = have;
|
19941 | _out = left;
|
19942 | ret = Z_OK;
|
19943 |
|
19944 | inf_leave: // goto emulation
|
19945 | for (;;) {
|
19946 | switch (state.mode) {
|
19947 | case HEAD:
|
19948 | if (state.wrap === 0) {
|
19949 | state.mode = TYPEDO;
|
19950 | break;
|
19951 | }
|
19952 | //=== NEEDBITS(16);
|
19953 | while (bits < 16) {
|
19954 | if (have === 0) { break inf_leave; }
|
19955 | have--;
|
19956 | hold += input[next++] << bits;
|
19957 | bits += 8;
|
19958 | }
|
19959 | //===//
|
19960 | if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
|
19961 | state.check = 0/*crc32(0L, Z_NULL, 0)*/;
|
19962 | //=== CRC2(state.check, hold);
|
19963 | hbuf[0] = hold & 0xff;
|
19964 | hbuf[1] = (hold >>> 8) & 0xff;
|
19965 | state.check = crc32(state.check, hbuf, 2, 0);
|
19966 | //===//
|
19967 |
|
19968 | //=== INITBITS();
|
19969 | hold = 0;
|
19970 | bits = 0;
|
19971 | //===//
|
19972 | state.mode = FLAGS;
|
19973 | break;
|
19974 | }
|
19975 | state.flags = 0; /* expect zlib header */
|
19976 | if (state.head) {
|
19977 | state.head.done = false;
|
19978 | }
|
19979 | if (!(state.wrap & 1) || /* check if zlib header allowed */
|
19980 | (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
|
19981 | strm.msg = 'incorrect header check';
|
19982 | state.mode = BAD;
|
19983 | break;
|
19984 | }
|
19985 | if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
|
19986 | strm.msg = 'unknown compression method';
|
19987 | state.mode = BAD;
|
19988 | break;
|
19989 | }
|
19990 | //--- DROPBITS(4) ---//
|
19991 | hold >>>= 4;
|
19992 | bits -= 4;
|
19993 | //---//
|
19994 | len = (hold & 0x0f)/*BITS(4)*/ + 8;
|
19995 | if (state.wbits === 0) {
|
19996 | state.wbits = len;
|
19997 | }
|
19998 | else if (len > state.wbits) {
|
19999 | strm.msg = 'invalid window size';
|
20000 | state.mode = BAD;
|
20001 | break;
|
20002 | }
|
20003 | state.dmax = 1 << len;
|
20004 | //Tracev((stderr, "inflate: zlib header ok\n"));
|
20005 | strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
|
20006 | state.mode = hold & 0x200 ? DICTID : TYPE;
|
20007 | //=== INITBITS();
|
20008 | hold = 0;
|
20009 | bits = 0;
|
20010 | //===//
|
20011 | break;
|
20012 | case FLAGS:
|
20013 | //=== NEEDBITS(16); */
|
20014 | while (bits < 16) {
|
20015 | if (have === 0) { break inf_leave; }
|
20016 | have--;
|
20017 | hold += input[next++] << bits;
|
20018 | bits += 8;
|
20019 | }
|
20020 | //===//
|
20021 | state.flags = hold;
|
20022 | if ((state.flags & 0xff) !== Z_DEFLATED) {
|
20023 | strm.msg = 'unknown compression method';
|
20024 | state.mode = BAD;
|
20025 | break;
|
20026 | }
|
20027 | if (state.flags & 0xe000) {
|
20028 | strm.msg = 'unknown header flags set';
|
20029 | state.mode = BAD;
|
20030 | break;
|
20031 | }
|
20032 | if (state.head) {
|
20033 | state.head.text = ((hold >> 8) & 1);
|
20034 | }
|
20035 | if (state.flags & 0x0200) {
|
20036 | //=== CRC2(state.check, hold);
|
20037 | hbuf[0] = hold & 0xff;
|
20038 | hbuf[1] = (hold >>> 8) & 0xff;
|
20039 | state.check = crc32(state.check, hbuf, 2, 0);
|
20040 | //===//
|
20041 | }
|
20042 | //=== INITBITS();
|
20043 | hold = 0;
|
20044 | bits = 0;
|
20045 | //===//
|
20046 | state.mode = TIME;
|
20047 | /* falls through */
|
20048 | case TIME:
|
20049 | //=== NEEDBITS(32); */
|
20050 | while (bits < 32) {
|
20051 | if (have === 0) { break inf_leave; }
|
20052 | have--;
|
20053 | hold += input[next++] << bits;
|
20054 | bits += 8;
|
20055 | }
|
20056 | //===//
|
20057 | if (state.head) {
|
20058 | state.head.time = hold;
|
20059 | }
|
20060 | if (state.flags & 0x0200) {
|
20061 | //=== CRC4(state.check, hold)
|
20062 | hbuf[0] = hold & 0xff;
|
20063 | hbuf[1] = (hold >>> 8) & 0xff;
|
20064 | hbuf[2] = (hold >>> 16) & 0xff;
|
20065 | hbuf[3] = (hold >>> 24) & 0xff;
|
20066 | state.check = crc32(state.check, hbuf, 4, 0);
|
20067 | //===
|
20068 | }
|
20069 | //=== INITBITS();
|
20070 | hold = 0;
|
20071 | bits = 0;
|
20072 | //===//
|
20073 | state.mode = OS;
|
20074 | /* falls through */
|
20075 | case OS:
|
20076 | //=== NEEDBITS(16); */
|
20077 | while (bits < 16) {
|
20078 | if (have === 0) { break inf_leave; }
|
20079 | have--;
|
20080 | hold += input[next++] << bits;
|
20081 | bits += 8;
|
20082 | }
|
20083 | //===//
|
20084 | if (state.head) {
|
20085 | state.head.xflags = (hold & 0xff);
|
20086 | state.head.os = (hold >> 8);
|
20087 | }
|
20088 | if (state.flags & 0x0200) {
|
20089 | //=== CRC2(state.check, hold);
|
20090 | hbuf[0] = hold & 0xff;
|
20091 | hbuf[1] = (hold >>> 8) & 0xff;
|
20092 | state.check = crc32(state.check, hbuf, 2, 0);
|
20093 | //===//
|
20094 | }
|
20095 | //=== INITBITS();
|
20096 | hold = 0;
|
20097 | bits = 0;
|
20098 | //===//
|
20099 | state.mode = EXLEN;
|
20100 | /* falls through */
|
20101 | case EXLEN:
|
20102 | if (state.flags & 0x0400) {
|
20103 | //=== NEEDBITS(16); */
|
20104 | while (bits < 16) {
|
20105 | if (have === 0) { break inf_leave; }
|
20106 | have--;
|
20107 | hold += input[next++] << bits;
|
20108 | bits += 8;
|
20109 | }
|
20110 | //===//
|
20111 | state.length = hold;
|
20112 | if (state.head) {
|
20113 | state.head.extra_len = hold;
|
20114 | }
|
20115 | if (state.flags & 0x0200) {
|
20116 | //=== CRC2(state.check, hold);
|
20117 | hbuf[0] = hold & 0xff;
|
20118 | hbuf[1] = (hold >>> 8) & 0xff;
|
20119 | state.check = crc32(state.check, hbuf, 2, 0);
|
20120 | //===//
|
20121 | }
|
20122 | //=== INITBITS();
|
20123 | hold = 0;
|
20124 | bits = 0;
|
20125 | //===//
|
20126 | }
|
20127 | else if (state.head) {
|
20128 | state.head.extra = null/*Z_NULL*/;
|
20129 | }
|
20130 | state.mode = EXTRA;
|
20131 | /* falls through */
|
20132 | case EXTRA:
|
20133 | if (state.flags & 0x0400) {
|
20134 | copy = state.length;
|
20135 | if (copy > have) { copy = have; }
|
20136 | if (copy) {
|
20137 | if (state.head) {
|
20138 | len = state.head.extra_len - state.length;
|
20139 | if (!state.head.extra) {
|
20140 | // Use untyped array for more conveniend processing later
|
20141 | state.head.extra = new Array(state.head.extra_len);
|
20142 | }
|
20143 | utils.arraySet(
|
20144 | state.head.extra,
|
20145 | input,
|
20146 | next,
|
20147 | // extra field is limited to 65536 bytes
|
20148 | // - no need for additional size check
|
20149 | copy,
|
20150 | /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
|
20151 | len
|
20152 | );
|
20153 | //zmemcpy(state.head.extra + len, next,
|
20154 | // len + copy > state.head.extra_max ?
|
20155 | // state.head.extra_max - len : copy);
|
20156 | }
|
20157 | if (state.flags & 0x0200) {
|
20158 | state.check = crc32(state.check, input, copy, next);
|
20159 | }
|
20160 | have -= copy;
|
20161 | next += copy;
|
20162 | state.length -= copy;
|
20163 | }
|
20164 | if (state.length) { break inf_leave; }
|
20165 | }
|
20166 | state.length = 0;
|
20167 | state.mode = NAME;
|
20168 | /* falls through */
|
20169 | case NAME:
|
20170 | if (state.flags & 0x0800) {
|
20171 | if (have === 0) { break inf_leave; }
|
20172 | copy = 0;
|
20173 | do {
|
20174 | // TODO: 2 or 1 bytes?
|
20175 | len = input[next + copy++];
|
20176 | /* use constant limit because in js we should not preallocate memory */
|
20177 | if (state.head && len &&
|
20178 | (state.length < 65536 /*state.head.name_max*/)) {
|
20179 | state.head.name += String.fromCharCode(len);
|
20180 | }
|
20181 | } while (len && copy < have);
|
20182 |
|
20183 | if (state.flags & 0x0200) {
|
20184 | state.check = crc32(state.check, input, copy, next);
|
20185 | }
|
20186 | have -= copy;
|
20187 | next += copy;
|
20188 | if (len) { break inf_leave; }
|
20189 | }
|
20190 | else if (state.head) {
|
20191 | state.head.name = null;
|
20192 | }
|
20193 | state.length = 0;
|
20194 | state.mode = COMMENT;
|
20195 | /* falls through */
|
20196 | case COMMENT:
|
20197 | if (state.flags & 0x1000) {
|
20198 | if (have === 0) { break inf_leave; }
|
20199 | copy = 0;
|
20200 | do {
|
20201 | len = input[next + copy++];
|
20202 | /* use constant limit because in js we should not preallocate memory */
|
20203 | if (state.head && len &&
|
20204 | (state.length < 65536 /*state.head.comm_max*/)) {
|
20205 | state.head.comment += String.fromCharCode(len);
|
20206 | }
|
20207 | } while (len && copy < have);
|
20208 | if (state.flags & 0x0200) {
|
20209 | state.check = crc32(state.check, input, copy, next);
|
20210 | }
|
20211 | have -= copy;
|
20212 | next += copy;
|
20213 | if (len) { break inf_leave; }
|
20214 | }
|
20215 | else if (state.head) {
|
20216 | state.head.comment = null;
|
20217 | }
|
20218 | state.mode = HCRC;
|
20219 | /* falls through */
|
20220 | case HCRC:
|
20221 | if (state.flags & 0x0200) {
|
20222 | //=== NEEDBITS(16); */
|
20223 | while (bits < 16) {
|
20224 | if (have === 0) { break inf_leave; }
|
20225 | have--;
|
20226 | hold += input[next++] << bits;
|
20227 | bits += 8;
|
20228 | }
|
20229 | //===//
|
20230 | if (hold !== (state.check & 0xffff)) {
|
20231 | strm.msg = 'header crc mismatch';
|
20232 | state.mode = BAD;
|
20233 | break;
|
20234 | }
|
20235 | //=== INITBITS();
|
20236 | hold = 0;
|
20237 | bits = 0;
|
20238 | //===//
|
20239 | }
|
20240 | if (state.head) {
|
20241 | state.head.hcrc = ((state.flags >> 9) & 1);
|
20242 | state.head.done = true;
|
20243 | }
|
20244 | strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
|
20245 | state.mode = TYPE;
|
20246 | break;
|
20247 | case DICTID:
|
20248 | //=== NEEDBITS(32); */
|
20249 | while (bits < 32) {
|
20250 | if (have === 0) { break inf_leave; }
|
20251 | have--;
|
20252 | hold += input[next++] << bits;
|
20253 | bits += 8;
|
20254 | }
|
20255 | //===//
|
20256 | strm.adler = state.check = ZSWAP32(hold);
|
20257 | //=== INITBITS();
|
20258 | hold = 0;
|
20259 | bits = 0;
|
20260 | //===//
|
20261 | state.mode = DICT;
|
20262 | /* falls through */
|
20263 | case DICT:
|
20264 | if (state.havedict === 0) {
|
20265 | //--- RESTORE() ---
|
20266 | strm.next_out = put;
|
20267 | strm.avail_out = left;
|
20268 | strm.next_in = next;
|
20269 | strm.avail_in = have;
|
20270 | state.hold = hold;
|
20271 | state.bits = bits;
|
20272 | //---
|
20273 | return Z_NEED_DICT;
|
20274 | }
|
20275 | strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
|
20276 | state.mode = TYPE;
|
20277 | /* falls through */
|
20278 | case TYPE:
|
20279 | if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
|
20280 | /* falls through */
|
20281 | case TYPEDO:
|
20282 | if (state.last) {
|
20283 | //--- BYTEBITS() ---//
|
20284 | hold >>>= bits & 7;
|
20285 | bits -= bits & 7;
|
20286 | //---//
|
20287 | state.mode = CHECK;
|
20288 | break;
|
20289 | }
|
20290 | //=== NEEDBITS(3); */
|
20291 | while (bits < 3) {
|
20292 | if (have === 0) { break inf_leave; }
|
20293 | have--;
|
20294 | hold += input[next++] << bits;
|
20295 | bits += 8;
|
20296 | }
|
20297 | //===//
|
20298 | state.last = (hold & 0x01)/*BITS(1)*/;
|
20299 | //--- DROPBITS(1) ---//
|
20300 | hold >>>= 1;
|
20301 | bits -= 1;
|
20302 | //---//
|
20303 |
|
20304 | switch ((hold & 0x03)/*BITS(2)*/) {
|
20305 | case 0: /* stored block */
|
20306 | //Tracev((stderr, "inflate: stored block%s\n",
|
20307 | // state.last ? " (last)" : ""));
|
20308 | state.mode = STORED;
|
20309 | break;
|
20310 | case 1: /* fixed block */
|
20311 | fixedtables(state);
|
20312 | //Tracev((stderr, "inflate: fixed codes block%s\n",
|
20313 | // state.last ? " (last)" : ""));
|
20314 | state.mode = LEN_; /* decode codes */
|
20315 | if (flush === Z_TREES) {
|
20316 | //--- DROPBITS(2) ---//
|
20317 | hold >>>= 2;
|
20318 | bits -= 2;
|
20319 | //---//
|
20320 | break inf_leave;
|
20321 | }
|
20322 | break;
|
20323 | case 2: /* dynamic block */
|
20324 | //Tracev((stderr, "inflate: dynamic codes block%s\n",
|
20325 | // state.last ? " (last)" : ""));
|
20326 | state.mode = TABLE;
|
20327 | break;
|
20328 | case 3:
|
20329 | strm.msg = 'invalid block type';
|
20330 | state.mode = BAD;
|
20331 | }
|
20332 | //--- DROPBITS(2) ---//
|
20333 | hold >>>= 2;
|
20334 | bits -= 2;
|
20335 | //---//
|
20336 | break;
|
20337 | case STORED:
|
20338 | //--- BYTEBITS() ---// /* go to byte boundary */
|
20339 | hold >>>= bits & 7;
|
20340 | bits -= bits & 7;
|
20341 | //---//
|
20342 | //=== NEEDBITS(32); */
|
20343 | while (bits < 32) {
|
20344 | if (have === 0) { break inf_leave; }
|
20345 | have--;
|
20346 | hold += input[next++] << bits;
|
20347 | bits += 8;
|
20348 | }
|
20349 | //===//
|
20350 | if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
|
20351 | strm.msg = 'invalid stored block lengths';
|
20352 | state.mode = BAD;
|
20353 | break;
|
20354 | }
|
20355 | state.length = hold & 0xffff;
|
20356 | //Tracev((stderr, "inflate: stored length %u\n",
|
20357 | // state.length));
|
20358 | //=== INITBITS();
|
20359 | hold = 0;
|
20360 | bits = 0;
|
20361 | //===//
|
20362 | state.mode = COPY_;
|
20363 | if (flush === Z_TREES) { break inf_leave; }
|
20364 | /* falls through */
|
20365 | case COPY_:
|
20366 | state.mode = COPY;
|
20367 | /* falls through */
|
20368 | case COPY:
|
20369 | copy = state.length;
|
20370 | if (copy) {
|
20371 | if (copy > have) { copy = have; }
|
20372 | if (copy > left) { copy = left; }
|
20373 | if (copy === 0) { break inf_leave; }
|
20374 | //--- zmemcpy(put, next, copy); ---
|
20375 | utils.arraySet(output, input, next, copy, put);
|
20376 | //---//
|
20377 | have -= copy;
|
20378 | next += copy;
|
20379 | left -= copy;
|
20380 | put += copy;
|
20381 | state.length -= copy;
|
20382 | break;
|
20383 | }
|
20384 | //Tracev((stderr, "inflate: stored end\n"));
|
20385 | state.mode = TYPE;
|
20386 | break;
|
20387 | case TABLE:
|
20388 | //=== NEEDBITS(14); */
|
20389 | while (bits < 14) {
|
20390 | if (have === 0) { break inf_leave; }
|
20391 | have--;
|
20392 | hold += input[next++] << bits;
|
20393 | bits += 8;
|
20394 | }
|
20395 | //===//
|
20396 | state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
|
20397 | //--- DROPBITS(5) ---//
|
20398 | hold >>>= 5;
|
20399 | bits -= 5;
|
20400 | //---//
|
20401 | state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
|
20402 | //--- DROPBITS(5) ---//
|
20403 | hold >>>= 5;
|
20404 | bits -= 5;
|
20405 | //---//
|
20406 | state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
|
20407 | //--- DROPBITS(4) ---//
|
20408 | hold >>>= 4;
|
20409 | bits -= 4;
|
20410 | //---//
|
20411 | //#ifndef PKZIP_BUG_WORKAROUND
|
20412 | if (state.nlen > 286 || state.ndist > 30) {
|
20413 | strm.msg = 'too many length or distance symbols';
|
20414 | state.mode = BAD;
|
20415 | break;
|
20416 | }
|
20417 | //#endif
|
20418 | //Tracev((stderr, "inflate: table sizes ok\n"));
|
20419 | state.have = 0;
|
20420 | state.mode = LENLENS;
|
20421 | /* falls through */
|
20422 | case LENLENS:
|
20423 | while (state.have < state.ncode) {
|
20424 | //=== NEEDBITS(3);
|
20425 | while (bits < 3) {
|
20426 | if (have === 0) { break inf_leave; }
|
20427 | have--;
|
20428 | hold += input[next++] << bits;
|
20429 | bits += 8;
|
20430 | }
|
20431 | //===//
|
20432 | state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
|
20433 | //--- DROPBITS(3) ---//
|
20434 | hold >>>= 3;
|
20435 | bits -= 3;
|
20436 | //---//
|
20437 | }
|
20438 | while (state.have < 19) {
|
20439 | state.lens[order[state.have++]] = 0;
|
20440 | }
|
20441 | // We have separate tables & no pointers. 2 commented lines below not needed.
|
20442 | //state.next = state.codes;
|
20443 | //state.lencode = state.next;
|
20444 | // Switch to use dynamic table
|
20445 | state.lencode = state.lendyn;
|
20446 | state.lenbits = 7;
|
20447 |
|
20448 | opts = {bits: state.lenbits};
|
20449 | ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
|
20450 | state.lenbits = opts.bits;
|
20451 |
|
20452 | if (ret) {
|
20453 | strm.msg = 'invalid code lengths set';
|
20454 | state.mode = BAD;
|
20455 | break;
|
20456 | }
|
20457 | //Tracev((stderr, "inflate: code lengths ok\n"));
|
20458 | state.have = 0;
|
20459 | state.mode = CODELENS;
|
20460 | /* falls through */
|
20461 | case CODELENS:
|
20462 | while (state.have < state.nlen + state.ndist) {
|
20463 | for (;;) {
|
20464 | here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
|
20465 | here_bits = here >>> 24;
|
20466 | here_op = (here >>> 16) & 0xff;
|
20467 | here_val = here & 0xffff;
|
20468 |
|
20469 | if ((here_bits) <= bits) { break; }
|
20470 | //--- PULLBYTE() ---//
|
20471 | if (have === 0) { break inf_leave; }
|
20472 | have--;
|
20473 | hold += input[next++] << bits;
|
20474 | bits += 8;
|
20475 | //---//
|
20476 | }
|
20477 | if (here_val < 16) {
|
20478 | //--- DROPBITS(here.bits) ---//
|
20479 | hold >>>= here_bits;
|
20480 | bits -= here_bits;
|
20481 | //---//
|
20482 | state.lens[state.have++] = here_val;
|
20483 | }
|
20484 | else {
|
20485 | if (here_val === 16) {
|
20486 | //=== NEEDBITS(here.bits + 2);
|
20487 | n = here_bits + 2;
|
20488 | while (bits < n) {
|
20489 | if (have === 0) { break inf_leave; }
|
20490 | have--;
|
20491 | hold += input[next++] << bits;
|
20492 | bits += 8;
|
20493 | }
|
20494 | //===//
|
20495 | //--- DROPBITS(here.bits) ---//
|
20496 | hold >>>= here_bits;
|
20497 | bits -= here_bits;
|
20498 | //---//
|
20499 | if (state.have === 0) {
|
20500 | strm.msg = 'invalid bit length repeat';
|
20501 | state.mode = BAD;
|
20502 | break;
|
20503 | }
|
20504 | len = state.lens[state.have - 1];
|
20505 | copy = 3 + (hold & 0x03);//BITS(2);
|
20506 | //--- DROPBITS(2) ---//
|
20507 | hold >>>= 2;
|
20508 | bits -= 2;
|
20509 | //---//
|
20510 | }
|
20511 | else if (here_val === 17) {
|
20512 | //=== NEEDBITS(here.bits + 3);
|
20513 | n = here_bits + 3;
|
20514 | while (bits < n) {
|
20515 | if (have === 0) { break inf_leave; }
|
20516 | have--;
|
20517 | hold += input[next++] << bits;
|
20518 | bits += 8;
|
20519 | }
|
20520 | //===//
|
20521 | //--- DROPBITS(here.bits) ---//
|
20522 | hold >>>= here_bits;
|
20523 | bits -= here_bits;
|
20524 | //---//
|
20525 | len = 0;
|
20526 | copy = 3 + (hold & 0x07);//BITS(3);
|
20527 | //--- DROPBITS(3) ---//
|
20528 | hold >>>= 3;
|
20529 | bits -= 3;
|
20530 | //---//
|
20531 | }
|
20532 | else {
|
20533 | //=== NEEDBITS(here.bits + 7);
|
20534 | n = here_bits + 7;
|
20535 | while (bits < n) {
|
20536 | if (have === 0) { break inf_leave; }
|
20537 | have--;
|
20538 | hold += input[next++] << bits;
|
20539 | bits += 8;
|
20540 | }
|
20541 | //===//
|
20542 | //--- DROPBITS(here.bits) ---//
|
20543 | hold >>>= here_bits;
|
20544 | bits -= here_bits;
|
20545 | //---//
|
20546 | len = 0;
|
20547 | copy = 11 + (hold & 0x7f);//BITS(7);
|
20548 | //--- DROPBITS(7) ---//
|
20549 | hold >>>= 7;
|
20550 | bits -= 7;
|
20551 | //---//
|
20552 | }
|
20553 | if (state.have + copy > state.nlen + state.ndist) {
|
20554 | strm.msg = 'invalid bit length repeat';
|
20555 | state.mode = BAD;
|
20556 | break;
|
20557 | }
|
20558 | while (copy--) {
|
20559 | state.lens[state.have++] = len;
|
20560 | }
|
20561 | }
|
20562 | }
|
20563 |
|
20564 | /* handle error breaks in while */
|
20565 | if (state.mode === BAD) { break; }
|
20566 |
|
20567 | /* check for end-of-block code (better have one) */
|
20568 | if (state.lens[256] === 0) {
|
20569 | strm.msg = 'invalid code -- missing end-of-block';
|
20570 | state.mode = BAD;
|
20571 | break;
|
20572 | }
|
20573 |
|
20574 | /* build code tables -- note: do not change the lenbits or distbits
|
20575 | values here (9 and 6) without reading the comments in inftrees.h
|
20576 | concerning the ENOUGH constants, which depend on those values */
|
20577 | state.lenbits = 9;
|
20578 |
|
20579 | opts = {bits: state.lenbits};
|
20580 | ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
|
20581 | // We have separate tables & no pointers. 2 commented lines below not needed.
|
20582 | // state.next_index = opts.table_index;
|
20583 | state.lenbits = opts.bits;
|
20584 | // state.lencode = state.next;
|
20585 |
|
20586 | if (ret) {
|
20587 | strm.msg = 'invalid literal/lengths set';
|
20588 | state.mode = BAD;
|
20589 | break;
|
20590 | }
|
20591 |
|
20592 | state.distbits = 6;
|
20593 | //state.distcode.copy(state.codes);
|
20594 | // Switch to use dynamic table
|
20595 | state.distcode = state.distdyn;
|
20596 | opts = {bits: state.distbits};
|
20597 | ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
|
20598 | // We have separate tables & no pointers. 2 commented lines below not needed.
|
20599 | // state.next_index = opts.table_index;
|
20600 | state.distbits = opts.bits;
|
20601 | // state.distcode = state.next;
|
20602 |
|
20603 | if (ret) {
|
20604 | strm.msg = 'invalid distances set';
|
20605 | state.mode = BAD;
|
20606 | break;
|
20607 | }
|
20608 | //Tracev((stderr, 'inflate: codes ok\n'));
|
20609 | state.mode = LEN_;
|
20610 | if (flush === Z_TREES) { break inf_leave; }
|
20611 | /* falls through */
|
20612 | case LEN_:
|
20613 | state.mode = LEN;
|
20614 | /* falls through */
|
20615 | case LEN:
|
20616 | if (have >= 6 && left >= 258) {
|
20617 | //--- RESTORE() ---
|
20618 | strm.next_out = put;
|
20619 | strm.avail_out = left;
|
20620 | strm.next_in = next;
|
20621 | strm.avail_in = have;
|
20622 | state.hold = hold;
|
20623 | state.bits = bits;
|
20624 | //---
|
20625 | inflate_fast(strm, _out);
|
20626 | //--- LOAD() ---
|
20627 | put = strm.next_out;
|
20628 | output = strm.output;
|
20629 | left = strm.avail_out;
|
20630 | next = strm.next_in;
|
20631 | input = strm.input;
|
20632 | have = strm.avail_in;
|
20633 | hold = state.hold;
|
20634 | bits = state.bits;
|
20635 | //---
|
20636 |
|
20637 | if (state.mode === TYPE) {
|
20638 | state.back = -1;
|
20639 | }
|
20640 | break;
|
20641 | }
|
20642 | state.back = 0;
|
20643 | for (;;) {
|
20644 | here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
|
20645 | here_bits = here >>> 24;
|
20646 | here_op = (here >>> 16) & 0xff;
|
20647 | here_val = here & 0xffff;
|
20648 |
|
20649 | if (here_bits <= bits) { break; }
|
20650 | //--- PULLBYTE() ---//
|
20651 | if (have === 0) { break inf_leave; }
|
20652 | have--;
|
20653 | hold += input[next++] << bits;
|
20654 | bits += 8;
|
20655 | //---//
|
20656 | }
|
20657 | if (here_op && (here_op & 0xf0) === 0) {
|
20658 | last_bits = here_bits;
|
20659 | last_op = here_op;
|
20660 | last_val = here_val;
|
20661 | for (;;) {
|
20662 | here = state.lencode[last_val +
|
20663 | ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
|
20664 | here_bits = here >>> 24;
|
20665 | here_op = (here >>> 16) & 0xff;
|
20666 | here_val = here & 0xffff;
|
20667 |
|
20668 | if ((last_bits + here_bits) <= bits) { break; }
|
20669 | //--- PULLBYTE() ---//
|
20670 | if (have === 0) { break inf_leave; }
|
20671 | have--;
|
20672 | hold += input[next++] << bits;
|
20673 | bits += 8;
|
20674 | //---//
|
20675 | }
|
20676 | //--- DROPBITS(last.bits) ---//
|
20677 | hold >>>= last_bits;
|
20678 | bits -= last_bits;
|
20679 | //---//
|
20680 | state.back += last_bits;
|
20681 | }
|
20682 | //--- DROPBITS(here.bits) ---//
|
20683 | hold >>>= here_bits;
|
20684 | bits -= here_bits;
|
20685 | //---//
|
20686 | state.back += here_bits;
|
20687 | state.length = here_val;
|
20688 | if (here_op === 0) {
|
20689 | //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
|
20690 | // "inflate: literal '%c'\n" :
|
20691 | // "inflate: literal 0x%02x\n", here.val));
|
20692 | state.mode = LIT;
|
20693 | break;
|
20694 | }
|
20695 | if (here_op & 32) {
|
20696 | //Tracevv((stderr, "inflate: end of block\n"));
|
20697 | state.back = -1;
|
20698 | state.mode = TYPE;
|
20699 | break;
|
20700 | }
|
20701 | if (here_op & 64) {
|
20702 | strm.msg = 'invalid literal/length code';
|
20703 | state.mode = BAD;
|
20704 | break;
|
20705 | }
|
20706 | state.extra = here_op & 15;
|
20707 | state.mode = LENEXT;
|
20708 | /* falls through */
|
20709 | case LENEXT:
|
20710 | if (state.extra) {
|
20711 | //=== NEEDBITS(state.extra);
|
20712 | n = state.extra;
|
20713 | while (bits < n) {
|
20714 | if (have === 0) { break inf_leave; }
|
20715 | have--;
|
20716 | hold += input[next++] << bits;
|
20717 | bits += 8;
|
20718 | }
|
20719 | //===//
|
20720 | state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
|
20721 | //--- DROPBITS(state.extra) ---//
|
20722 | hold >>>= state.extra;
|
20723 | bits -= state.extra;
|
20724 | //---//
|
20725 | state.back += state.extra;
|
20726 | }
|
20727 | //Tracevv((stderr, "inflate: length %u\n", state.length));
|
20728 | state.was = state.length;
|
20729 | state.mode = DIST;
|
20730 | /* falls through */
|
20731 | case DIST:
|
20732 | for (;;) {
|
20733 | here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
|
20734 | here_bits = here >>> 24;
|
20735 | here_op = (here >>> 16) & 0xff;
|
20736 | here_val = here & 0xffff;
|
20737 |
|
20738 | if ((here_bits) <= bits) { break; }
|
20739 | //--- PULLBYTE() ---//
|
20740 | if (have === 0) { break inf_leave; }
|
20741 | have--;
|
20742 | hold += input[next++] << bits;
|
20743 | bits += 8;
|
20744 | //---//
|
20745 | }
|
20746 | if ((here_op & 0xf0) === 0) {
|
20747 | last_bits = here_bits;
|
20748 | last_op = here_op;
|
20749 | last_val = here_val;
|
20750 | for (;;) {
|
20751 | here = state.distcode[last_val +
|
20752 | ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
|
20753 | here_bits = here >>> 24;
|
20754 | here_op = (here >>> 16) & 0xff;
|
20755 | here_val = here & 0xffff;
|
20756 |
|
20757 | if ((last_bits + here_bits) <= bits) { break; }
|
20758 | //--- PULLBYTE() ---//
|
20759 | if (have === 0) { break inf_leave; }
|
20760 | have--;
|
20761 | hold += input[next++] << bits;
|
20762 | bits += 8;
|
20763 | //---//
|
20764 | }
|
20765 | //--- DROPBITS(last.bits) ---//
|
20766 | hold >>>= last_bits;
|
20767 | bits -= last_bits;
|
20768 | //---//
|
20769 | state.back += last_bits;
|
20770 | }
|
20771 | //--- DROPBITS(here.bits) ---//
|
20772 | hold >>>= here_bits;
|
20773 | bits -= here_bits;
|
20774 | //---//
|
20775 | state.back += here_bits;
|
20776 | if (here_op & 64) {
|
20777 | strm.msg = 'invalid distance code';
|
20778 | state.mode = BAD;
|
20779 | break;
|
20780 | }
|
20781 | state.offset = here_val;
|
20782 | state.extra = (here_op) & 15;
|
20783 | state.mode = DISTEXT;
|
20784 | /* falls through */
|
20785 | case DISTEXT:
|
20786 | if (state.extra) {
|
20787 | //=== NEEDBITS(state.extra);
|
20788 | n = state.extra;
|
20789 | while (bits < n) {
|
20790 | if (have === 0) { break inf_leave; }
|
20791 | have--;
|
20792 | hold += input[next++] << bits;
|
20793 | bits += 8;
|
20794 | }
|
20795 | //===//
|
20796 | state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
|
20797 | //--- DROPBITS(state.extra) ---//
|
20798 | hold >>>= state.extra;
|
20799 | bits -= state.extra;
|
20800 | //---//
|
20801 | state.back += state.extra;
|
20802 | }
|
20803 | //#ifdef INFLATE_STRICT
|
20804 | if (state.offset > state.dmax) {
|
20805 | strm.msg = 'invalid distance too far back';
|
20806 | state.mode = BAD;
|
20807 | break;
|
20808 | }
|
20809 | //#endif
|
20810 | //Tracevv((stderr, "inflate: distance %u\n", state.offset));
|
20811 | state.mode = MATCH;
|
20812 | /* falls through */
|
20813 | case MATCH:
|
20814 | if (left === 0) { break inf_leave; }
|
20815 | copy = _out - left;
|
20816 | if (state.offset > copy) { /* copy from window */
|
20817 | copy = state.offset - copy;
|
20818 | if (copy > state.whave) {
|
20819 | if (state.sane) {
|
20820 | strm.msg = 'invalid distance too far back';
|
20821 | state.mode = BAD;
|
20822 | break;
|
20823 | }
|
20824 | // (!) This block is disabled in zlib defailts,
|
20825 | // don't enable it for binary compatibility
|
20826 | //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
|
20827 | // Trace((stderr, "inflate.c too far\n"));
|
20828 | // copy -= state.whave;
|
20829 | // if (copy > state.length) { copy = state.length; }
|
20830 | // if (copy > left) { copy = left; }
|
20831 | // left -= copy;
|
20832 | // state.length -= copy;
|
20833 | // do {
|
20834 | // output[put++] = 0;
|
20835 | // } while (--copy);
|
20836 | // if (state.length === 0) { state.mode = LEN; }
|
20837 | // break;
|
20838 | //#endif
|
20839 | }
|
20840 | if (copy > state.wnext) {
|
20841 | copy -= state.wnext;
|
20842 | from = state.wsize - copy;
|
20843 | }
|
20844 | else {
|
20845 | from = state.wnext - copy;
|
20846 | }
|
20847 | if (copy > state.length) { copy = state.length; }
|
20848 | from_source = state.window;
|
20849 | }
|
20850 | else { /* copy from output */
|
20851 | from_source = output;
|
20852 | from = put - state.offset;
|
20853 | copy = state.length;
|
20854 | }
|
20855 | if (copy > left) { copy = left; }
|
20856 | left -= copy;
|
20857 | state.length -= copy;
|
20858 | do {
|
20859 | output[put++] = from_source[from++];
|
20860 | } while (--copy);
|
20861 | if (state.length === 0) { state.mode = LEN; }
|
20862 | break;
|
20863 | case LIT:
|
20864 | if (left === 0) { break inf_leave; }
|
20865 | output[put++] = state.length;
|
20866 | left--;
|
20867 | state.mode = LEN;
|
20868 | break;
|
20869 | case CHECK:
|
20870 | if (state.wrap) {
|
20871 | //=== NEEDBITS(32);
|
20872 | while (bits < 32) {
|
20873 | if (have === 0) { break inf_leave; }
|
20874 | have--;
|
20875 | // Use '|' insdead of '+' to make sure that result is signed
|
20876 | hold |= input[next++] << bits;
|
20877 | bits += 8;
|
20878 | }
|
20879 | //===//
|
20880 | _out -= left;
|
20881 | strm.total_out += _out;
|
20882 | state.total += _out;
|
20883 | if (_out) {
|
20884 | strm.adler = state.check =
|
20885 | /*UPDATE(state.check, put - _out, _out);*/
|
20886 | (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
|
20887 |
|
20888 | }
|
20889 | _out = left;
|
20890 | // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
|
20891 | if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
|
20892 | strm.msg = 'incorrect data check';
|
20893 | state.mode = BAD;
|
20894 | break;
|
20895 | }
|
20896 | //=== INITBITS();
|
20897 | hold = 0;
|
20898 | bits = 0;
|
20899 | //===//
|
20900 | //Tracev((stderr, "inflate: check matches trailer\n"));
|
20901 | }
|
20902 | state.mode = LENGTH;
|
20903 | /* falls through */
|
20904 | case LENGTH:
|
20905 | if (state.wrap && state.flags) {
|
20906 | //=== NEEDBITS(32);
|
20907 | while (bits < 32) {
|
20908 | if (have === 0) { break inf_leave; }
|
20909 | have--;
|
20910 | hold += input[next++] << bits;
|
20911 | bits += 8;
|
20912 | }
|
20913 | //===//
|
20914 | if (hold !== (state.total & 0xffffffff)) {
|
20915 | strm.msg = 'incorrect length check';
|
20916 | state.mode = BAD;
|
20917 | break;
|
20918 | }
|
20919 | //=== INITBITS();
|
20920 | hold = 0;
|
20921 | bits = 0;
|
20922 | //===//
|
20923 | //Tracev((stderr, "inflate: length matches trailer\n"));
|
20924 | }
|
20925 | state.mode = DONE;
|
20926 | /* falls through */
|
20927 | case DONE:
|
20928 | ret = Z_STREAM_END;
|
20929 | break inf_leave;
|
20930 | case BAD:
|
20931 | ret = Z_DATA_ERROR;
|
20932 | break inf_leave;
|
20933 | case MEM:
|
20934 | return Z_MEM_ERROR;
|
20935 | case SYNC:
|
20936 | /* falls through */
|
20937 | default:
|
20938 | return Z_STREAM_ERROR;
|
20939 | }
|
20940 | }
|
20941 |
|
20942 | // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
|
20943 |
|
20944 | /*
|
20945 | Return from inflate(), updating the total counts and the check value.
|
20946 | If there was no progress during the inflate() call, return a buffer
|
20947 | error. Call updatewindow() to create and/or update the window state.
|
20948 | Note: a memory error from inflate() is non-recoverable.
|
20949 | */
|
20950 |
|
20951 | //--- RESTORE() ---
|
20952 | strm.next_out = put;
|
20953 | strm.avail_out = left;
|
20954 | strm.next_in = next;
|
20955 | strm.avail_in = have;
|
20956 | state.hold = hold;
|
20957 | state.bits = bits;
|
20958 | //---
|
20959 |
|
20960 | if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
|
20961 | (state.mode < CHECK || flush !== Z_FINISH))) {
|
20962 | if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
|
20963 | state.mode = MEM;
|
20964 | return Z_MEM_ERROR;
|
20965 | }
|
20966 | }
|
20967 | _in -= strm.avail_in;
|
20968 | _out -= strm.avail_out;
|
20969 | strm.total_in += _in;
|
20970 | strm.total_out += _out;
|
20971 | state.total += _out;
|
20972 | if (state.wrap && _out) {
|
20973 | strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
|
20974 | (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
|
20975 | }
|
20976 | strm.data_type = state.bits + (state.last ? 64 : 0) +
|
20977 | (state.mode === TYPE ? 128 : 0) +
|
20978 | (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
|
20979 | if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
|
20980 | ret = Z_BUF_ERROR;
|
20981 | }
|
20982 | return ret;
|
20983 | }
|
20984 |
|
20985 | function inflateEnd(strm) {
|
20986 |
|
20987 | if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
|
20988 | return Z_STREAM_ERROR;
|
20989 | }
|
20990 |
|
20991 | var state = strm.state;
|
20992 | if (state.window) {
|
20993 | state.window = null;
|
20994 | }
|
20995 | strm.state = null;
|
20996 | return Z_OK;
|
20997 | }
|
20998 |
|
20999 | function inflateGetHeader(strm, head) {
|
21000 | var state;
|
21001 |
|
21002 | /* check state */
|
21003 | if (!strm || !strm.state) { return Z_STREAM_ERROR; }
|
21004 | state = strm.state;
|
21005 | if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
|
21006 |
|
21007 | /* save header structure */
|
21008 | state.head = head;
|
21009 | head.done = false;
|
21010 | return Z_OK;
|
21011 | }
|
21012 |
|
21013 |
|
21014 | exports.inflateReset = inflateReset;
|
21015 | exports.inflateReset2 = inflateReset2;
|
21016 | exports.inflateResetKeep = inflateResetKeep;
|
21017 | exports.inflateInit = inflateInit;
|
21018 | exports.inflateInit2 = inflateInit2;
|
21019 | exports.inflate = inflate;
|
21020 | exports.inflateEnd = inflateEnd;
|
21021 | exports.inflateGetHeader = inflateGetHeader;
|
21022 | exports.inflateInfo = 'pako inflate (from Nodeca project)';
|
21023 |
|
21024 | /* Not implemented
|
21025 | exports.inflateCopy = inflateCopy;
|
21026 | exports.inflateGetDictionary = inflateGetDictionary;
|
21027 | exports.inflateMark = inflateMark;
|
21028 | exports.inflatePrime = inflatePrime;
|
21029 | exports.inflateSetDictionary = inflateSetDictionary;
|
21030 | exports.inflateSync = inflateSync;
|
21031 | exports.inflateSyncPoint = inflateSyncPoint;
|
21032 | exports.inflateUndermine = inflateUndermine;
|
21033 | */
|
21034 |
|
21035 | },{"../utils/common":14,"./adler32":16,"./crc32":18,"./inffast":21,"./inftrees":23}],23:[function(require,module,exports){
|
21036 | 'use strict';
|
21037 |
|
21038 |
|
21039 | var utils = require('../utils/common');
|
21040 |
|
21041 | var MAXBITS = 15;
|
21042 | var ENOUGH_LENS = 852;
|
21043 | var ENOUGH_DISTS = 592;
|
21044 | //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
|
21045 |
|
21046 | var CODES = 0;
|
21047 | var LENS = 1;
|
21048 | var DISTS = 2;
|
21049 |
|
21050 | var lbase = [ /* Length codes 257..285 base */
|
21051 | 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
|
21052 | 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
|
21053 | ];
|
21054 |
|
21055 | var lext = [ /* Length codes 257..285 extra */
|
21056 | 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
|
21057 | 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
|
21058 | ];
|
21059 |
|
21060 | var dbase = [ /* Distance codes 0..29 base */
|
21061 | 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
|
21062 | 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
|
21063 | 8193, 12289, 16385, 24577, 0, 0
|
21064 | ];
|
21065 |
|
21066 | var dext = [ /* Distance codes 0..29 extra */
|
21067 | 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
|
21068 | 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
|
21069 | 28, 28, 29, 29, 64, 64
|
21070 | ];
|
21071 |
|
21072 | module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
|
21073 | {
|
21074 | var bits = opts.bits;
|
21075 | //here = opts.here; /* table entry for duplication */
|
21076 |
|
21077 | var len = 0; /* a code's length in bits */
|
21078 | var sym = 0; /* index of code symbols */
|
21079 | var min = 0, max = 0; /* minimum and maximum code lengths */
|
21080 | var root = 0; /* number of index bits for root table */
|
21081 | var curr = 0; /* number of index bits for current table */
|
21082 | var drop = 0; /* code bits to drop for sub-table */
|
21083 | var left = 0; /* number of prefix codes available */
|
21084 | var used = 0; /* code entries in table used */
|
21085 | var huff = 0; /* Huffman code */
|
21086 | var incr; /* for incrementing code, index */
|
21087 | var fill; /* index for replicating entries */
|
21088 | var low; /* low bits for current root entry */
|
21089 | var mask; /* mask for low root bits */
|
21090 | var next; /* next available space in table */
|
21091 | var base = null; /* base value table to use */
|
21092 | var base_index = 0;
|
21093 | // var shoextra; /* extra bits table to use */
|
21094 | var end; /* use base and extra for symbol > end */
|
21095 | var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
|
21096 | var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
|
21097 | var extra = null;
|
21098 | var extra_index = 0;
|
21099 |
|
21100 | var here_bits, here_op, here_val;
|
21101 |
|
21102 | /*
|
21103 | Process a set of code lengths to create a canonical Huffman code. The
|
21104 | code lengths are lens[0..codes-1]. Each length corresponds to the
|
21105 | symbols 0..codes-1. The Huffman code is generated by first sorting the
|
21106 | symbols by length from short to long, and retaining the symbol order
|
21107 | for codes with equal lengths. Then the code starts with all zero bits
|
21108 | for the first code of the shortest length, and the codes are integer
|
21109 | increments for the same length, and zeros are appended as the length
|
21110 | increases. For the deflate format, these bits are stored backwards
|
21111 | from their more natural integer increment ordering, and so when the
|
21112 | decoding tables are built in the large loop below, the integer codes
|
21113 | are incremented backwards.
|
21114 |
|
21115 | This routine assumes, but does not check, that all of the entries in
|
21116 | lens[] are in the range 0..MAXBITS. The caller must assure this.
|
21117 | 1..MAXBITS is interpreted as that code length. zero means that that
|
21118 | symbol does not occur in this code.
|
21119 |
|
21120 | The codes are sorted by computing a count of codes for each length,
|
21121 | creating from that a table of starting indices for each length in the
|
21122 | sorted table, and then entering the symbols in order in the sorted
|
21123 | table. The sorted table is work[], with that space being provided by
|
21124 | the caller.
|
21125 |
|
21126 | The length counts are used for other purposes as well, i.e. finding
|
21127 | the minimum and maximum length codes, determining if there are any
|
21128 | codes at all, checking for a valid set of lengths, and looking ahead
|
21129 | at length counts to determine sub-table sizes when building the
|
21130 | decoding tables.
|
21131 | */
|
21132 |
|
21133 | /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
|
21134 | for (len = 0; len <= MAXBITS; len++) {
|
21135 | count[len] = 0;
|
21136 | }
|
21137 | for (sym = 0; sym < codes; sym++) {
|
21138 | count[lens[lens_index + sym]]++;
|
21139 | }
|
21140 |
|
21141 | /* bound code lengths, force root to be within code lengths */
|
21142 | root = bits;
|
21143 | for (max = MAXBITS; max >= 1; max--) {
|
21144 | if (count[max] !== 0) { break; }
|
21145 | }
|
21146 | if (root > max) {
|
21147 | root = max;
|
21148 | }
|
21149 | if (max === 0) { /* no symbols to code at all */
|
21150 | //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
|
21151 | //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
|
21152 | //table.val[opts.table_index++] = 0; //here.val = (var short)0;
|
21153 | table[table_index++] = (1 << 24) | (64 << 16) | 0;
|
21154 |
|
21155 |
|
21156 | //table.op[opts.table_index] = 64;
|
21157 | //table.bits[opts.table_index] = 1;
|
21158 | //table.val[opts.table_index++] = 0;
|
21159 | table[table_index++] = (1 << 24) | (64 << 16) | 0;
|
21160 |
|
21161 | opts.bits = 1;
|
21162 | return 0; /* no symbols, but wait for decoding to report error */
|
21163 | }
|
21164 | for (min = 1; min < max; min++) {
|
21165 | if (count[min] !== 0) { break; }
|
21166 | }
|
21167 | if (root < min) {
|
21168 | root = min;
|
21169 | }
|
21170 |
|
21171 | /* check for an over-subscribed or incomplete set of lengths */
|
21172 | left = 1;
|
21173 | for (len = 1; len <= MAXBITS; len++) {
|
21174 | left <<= 1;
|
21175 | left -= count[len];
|
21176 | if (left < 0) {
|
21177 | return -1;
|
21178 | } /* over-subscribed */
|
21179 | }
|
21180 | if (left > 0 && (type === CODES || max !== 1)) {
|
21181 | return -1; /* incomplete set */
|
21182 | }
|
21183 |
|
21184 | /* generate offsets into symbol table for each length for sorting */
|
21185 | offs[1] = 0;
|
21186 | for (len = 1; len < MAXBITS; len++) {
|
21187 | offs[len + 1] = offs[len] + count[len];
|
21188 | }
|
21189 |
|
21190 | /* sort symbols by length, by symbol order within each length */
|
21191 | for (sym = 0; sym < codes; sym++) {
|
21192 | if (lens[lens_index + sym] !== 0) {
|
21193 | work[offs[lens[lens_index + sym]]++] = sym;
|
21194 | }
|
21195 | }
|
21196 |
|
21197 | /*
|
21198 | Create and fill in decoding tables. In this loop, the table being
|
21199 | filled is at next and has curr index bits. The code being used is huff
|
21200 | with length len. That code is converted to an index by dropping drop
|
21201 | bits off of the bottom. For codes where len is less than drop + curr,
|
21202 | those top drop + curr - len bits are incremented through all values to
|
21203 | fill the table with replicated entries.
|
21204 |
|
21205 | root is the number of index bits for the root table. When len exceeds
|
21206 | root, sub-tables are created pointed to by the root entry with an index
|
21207 | of the low root bits of huff. This is saved in low to check for when a
|
21208 | new sub-table should be started. drop is zero when the root table is
|
21209 | being filled, and drop is root when sub-tables are being filled.
|
21210 |
|
21211 | When a new sub-table is needed, it is necessary to look ahead in the
|
21212 | code lengths to determine what size sub-table is needed. The length
|
21213 | counts are used for this, and so count[] is decremented as codes are
|
21214 | entered in the tables.
|
21215 |
|
21216 | used keeps track of how many table entries have been allocated from the
|
21217 | provided *table space. It is checked for LENS and DIST tables against
|
21218 | the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
|
21219 | the initial root table size constants. See the comments in inftrees.h
|
21220 | for more information.
|
21221 |
|
21222 | sym increments through all symbols, and the loop terminates when
|
21223 | all codes of length max, i.e. all codes, have been processed. This
|
21224 | routine permits incomplete codes, so another loop after this one fills
|
21225 | in the rest of the decoding tables with invalid code markers.
|
21226 | */
|
21227 |
|
21228 | /* set up for code type */
|
21229 | // poor man optimization - use if-else instead of switch,
|
21230 | // to avoid deopts in old v8
|
21231 | if (type === CODES) {
|
21232 | base = extra = work; /* dummy value--not used */
|
21233 | end = 19;
|
21234 |
|
21235 | } else if (type === LENS) {
|
21236 | base = lbase;
|
21237 | base_index -= 257;
|
21238 | extra = lext;
|
21239 | extra_index -= 257;
|
21240 | end = 256;
|
21241 |
|
21242 | } else { /* DISTS */
|
21243 | base = dbase;
|
21244 | extra = dext;
|
21245 | end = -1;
|
21246 | }
|
21247 |
|
21248 | /* initialize opts for loop */
|
21249 | huff = 0; /* starting code */
|
21250 | sym = 0; /* starting code symbol */
|
21251 | len = min; /* starting code length */
|
21252 | next = table_index; /* current table to fill in */
|
21253 | curr = root; /* current table index bits */
|
21254 | drop = 0; /* current bits to drop from code for index */
|
21255 | low = -1; /* trigger new sub-table when len > root */
|
21256 | used = 1 << root; /* use root table entries */
|
21257 | mask = used - 1; /* mask for comparing low */
|
21258 |
|
21259 | /* check available table space */
|
21260 | if ((type === LENS && used > ENOUGH_LENS) ||
|
21261 | (type === DISTS && used > ENOUGH_DISTS)) {
|
21262 | return 1;
|
21263 | }
|
21264 |
|
21265 | var i=0;
|
21266 | /* process all codes and make table entries */
|
21267 | for (;;) {
|
21268 | i++;
|
21269 | /* create table entry */
|
21270 | here_bits = len - drop;
|
21271 | if (work[sym] < end) {
|
21272 | here_op = 0;
|
21273 | here_val = work[sym];
|
21274 | }
|
21275 | else if (work[sym] > end) {
|
21276 | here_op = extra[extra_index + work[sym]];
|
21277 | here_val = base[base_index + work[sym]];
|
21278 | }
|
21279 | else {
|
21280 | here_op = 32 + 64; /* end of block */
|
21281 | here_val = 0;
|
21282 | }
|
21283 |
|
21284 | /* replicate for those indices with low len bits equal to huff */
|
21285 | incr = 1 << (len - drop);
|
21286 | fill = 1 << curr;
|
21287 | min = fill; /* save offset to next table */
|
21288 | do {
|
21289 | fill -= incr;
|
21290 | table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
|
21291 | } while (fill !== 0);
|
21292 |
|
21293 | /* backwards increment the len-bit code huff */
|
21294 | incr = 1 << (len - 1);
|
21295 | while (huff & incr) {
|
21296 | incr >>= 1;
|
21297 | }
|
21298 | if (incr !== 0) {
|
21299 | huff &= incr - 1;
|
21300 | huff += incr;
|
21301 | } else {
|
21302 | huff = 0;
|
21303 | }
|
21304 |
|
21305 | /* go to next symbol, update count, len */
|
21306 | sym++;
|
21307 | if (--count[len] === 0) {
|
21308 | if (len === max) { break; }
|
21309 | len = lens[lens_index + work[sym]];
|
21310 | }
|
21311 |
|
21312 | /* create new sub-table if needed */
|
21313 | if (len > root && (huff & mask) !== low) {
|
21314 | /* if first time, transition to sub-tables */
|
21315 | if (drop === 0) {
|
21316 | drop = root;
|
21317 | }
|
21318 |
|
21319 | /* increment past last table */
|
21320 | next += min; /* here min is 1 << curr */
|
21321 |
|
21322 | /* determine length of next table */
|
21323 | curr = len - drop;
|
21324 | left = 1 << curr;
|
21325 | while (curr + drop < max) {
|
21326 | left -= count[curr + drop];
|
21327 | if (left <= 0) { break; }
|
21328 | curr++;
|
21329 | left <<= 1;
|
21330 | }
|
21331 |
|
21332 | /* check for enough space */
|
21333 | used += 1 << curr;
|
21334 | if ((type === LENS && used > ENOUGH_LENS) ||
|
21335 | (type === DISTS && used > ENOUGH_DISTS)) {
|
21336 | return 1;
|
21337 | }
|
21338 |
|
21339 | /* point entry in root table to sub-table */
|
21340 | low = huff & mask;
|
21341 | /*table.op[low] = curr;
|
21342 | table.bits[low] = root;
|
21343 | table.val[low] = next - opts.table_index;*/
|
21344 | table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
|
21345 | }
|
21346 | }
|
21347 |
|
21348 | /* fill in remaining table entry if code is incomplete (guaranteed to have
|
21349 | at most one remaining entry, since if the code is incomplete, the
|
21350 | maximum code length that was allowed to get this far is one bit) */
|
21351 | if (huff !== 0) {
|
21352 | //table.op[next + huff] = 64; /* invalid code marker */
|
21353 | //table.bits[next + huff] = len - drop;
|
21354 | //table.val[next + huff] = 0;
|
21355 | table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
|
21356 | }
|
21357 |
|
21358 | /* set return parameters */
|
21359 | //opts.table_index += used;
|
21360 | opts.bits = root;
|
21361 | return 0;
|
21362 | };
|
21363 |
|
21364 | },{"../utils/common":14}],24:[function(require,module,exports){
|
21365 | 'use strict';
|
21366 |
|
21367 | module.exports = {
|
21368 | '2': 'need dictionary', /* Z_NEED_DICT 2 */
|
21369 | '1': 'stream end', /* Z_STREAM_END 1 */
|
21370 | '0': '', /* Z_OK 0 */
|
21371 | '-1': 'file error', /* Z_ERRNO (-1) */
|
21372 | '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
|
21373 | '-3': 'data error', /* Z_DATA_ERROR (-3) */
|
21374 | '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
|
21375 | '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
|
21376 | '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
|
21377 | };
|
21378 |
|
21379 | },{}],25:[function(require,module,exports){
|
21380 | 'use strict';
|
21381 |
|
21382 |
|
21383 | var utils = require('../utils/common');
|
21384 |
|
21385 | /* Public constants ==========================================================*/
|
21386 | /* ===========================================================================*/
|
21387 |
|
21388 |
|
21389 | //var Z_FILTERED = 1;
|
21390 | //var Z_HUFFMAN_ONLY = 2;
|
21391 | //var Z_RLE = 3;
|
21392 | var Z_FIXED = 4;
|
21393 | //var Z_DEFAULT_STRATEGY = 0;
|
21394 |
|
21395 | /* Possible values of the data_type field (though see inflate()) */
|
21396 | var Z_BINARY = 0;
|
21397 | var Z_TEXT = 1;
|
21398 | //var Z_ASCII = 1; // = Z_TEXT
|
21399 | var Z_UNKNOWN = 2;
|
21400 |
|
21401 | /*============================================================================*/
|
21402 |
|
21403 |
|
21404 | function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
|
21405 |
|
21406 | // From zutil.h
|
21407 |
|
21408 | var STORED_BLOCK = 0;
|
21409 | var STATIC_TREES = 1;
|
21410 | var DYN_TREES = 2;
|
21411 | /* The three kinds of block type */
|
21412 |
|
21413 | var MIN_MATCH = 3;
|
21414 | var MAX_MATCH = 258;
|
21415 | /* The minimum and maximum match lengths */
|
21416 |
|
21417 | // From deflate.h
|
21418 | /* ===========================================================================
|
21419 | * Internal compression state.
|
21420 | */
|
21421 |
|
21422 | var LENGTH_CODES = 29;
|
21423 | /* number of length codes, not counting the special END_BLOCK code */
|
21424 |
|
21425 | var LITERALS = 256;
|
21426 | /* number of literal bytes 0..255 */
|
21427 |
|
21428 | var L_CODES = LITERALS + 1 + LENGTH_CODES;
|
21429 | /* number of Literal or Length codes, including the END_BLOCK code */
|
21430 |
|
21431 | var D_CODES = 30;
|
21432 | /* number of distance codes */
|
21433 |
|
21434 | var BL_CODES = 19;
|
21435 | /* number of codes used to transfer the bit lengths */
|
21436 |
|
21437 | var HEAP_SIZE = 2*L_CODES + 1;
|
21438 | /* maximum heap size */
|
21439 |
|
21440 | var MAX_BITS = 15;
|
21441 | /* All codes must not exceed MAX_BITS bits */
|
21442 |
|
21443 | var Buf_size = 16;
|
21444 | /* size of bit buffer in bi_buf */
|
21445 |
|
21446 |
|
21447 | /* ===========================================================================
|
21448 | * Constants
|
21449 | */
|
21450 |
|
21451 | var MAX_BL_BITS = 7;
|
21452 | /* Bit length codes must not exceed MAX_BL_BITS bits */
|
21453 |
|
21454 | var END_BLOCK = 256;
|
21455 | /* end of block literal code */
|
21456 |
|
21457 | var REP_3_6 = 16;
|
21458 | /* repeat previous bit length 3-6 times (2 bits of repeat count) */
|
21459 |
|
21460 | var REPZ_3_10 = 17;
|
21461 | /* repeat a zero length 3-10 times (3 bits of repeat count) */
|
21462 |
|
21463 | var REPZ_11_138 = 18;
|
21464 | /* repeat a zero length 11-138 times (7 bits of repeat count) */
|
21465 |
|
21466 | var extra_lbits = /* extra bits for each length code */
|
21467 | [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
|
21468 |
|
21469 | var extra_dbits = /* extra bits for each distance code */
|
21470 | [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
|
21471 |
|
21472 | var extra_blbits = /* extra bits for each bit length code */
|
21473 | [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
|
21474 |
|
21475 | var bl_order =
|
21476 | [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
|
21477 | /* The lengths of the bit length codes are sent in order of decreasing
|
21478 | * probability, to avoid transmitting the lengths for unused bit length codes.
|
21479 | */
|
21480 |
|
21481 | /* ===========================================================================
|
21482 | * Local data. These are initialized only once.
|
21483 | */
|
21484 |
|
21485 | // We pre-fill arrays with 0 to avoid uninitialized gaps
|
21486 |
|
21487 | var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
|
21488 |
|
21489 | // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
|
21490 | var static_ltree = new Array((L_CODES+2) * 2);
|
21491 | zero(static_ltree);
|
21492 | /* The static literal tree. Since the bit lengths are imposed, there is no
|
21493 | * need for the L_CODES extra codes used during heap construction. However
|
21494 | * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
|
21495 | * below).
|
21496 | */
|
21497 |
|
21498 | var static_dtree = new Array(D_CODES * 2);
|
21499 | zero(static_dtree);
|
21500 | /* The static distance tree. (Actually a trivial tree since all codes use
|
21501 | * 5 bits.)
|
21502 | */
|
21503 |
|
21504 | var _dist_code = new Array(DIST_CODE_LEN);
|
21505 | zero(_dist_code);
|
21506 | /* Distance codes. The first 256 values correspond to the distances
|
21507 | * 3 .. 258, the last 256 values correspond to the top 8 bits of
|
21508 | * the 15 bit distances.
|
21509 | */
|
21510 |
|
21511 | var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
|
21512 | zero(_length_code);
|
21513 | /* length code for each normalized match length (0 == MIN_MATCH) */
|
21514 |
|
21515 | var base_length = new Array(LENGTH_CODES);
|
21516 | zero(base_length);
|
21517 | /* First normalized length for each code (0 = MIN_MATCH) */
|
21518 |
|
21519 | var base_dist = new Array(D_CODES);
|
21520 | zero(base_dist);
|
21521 | /* First normalized distance for each code (0 = distance of 1) */
|
21522 |
|
21523 |
|
21524 | var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
|
21525 |
|
21526 | this.static_tree = static_tree; /* static tree or NULL */
|
21527 | this.extra_bits = extra_bits; /* extra bits for each code or NULL */
|
21528 | this.extra_base = extra_base; /* base index for extra_bits */
|
21529 | this.elems = elems; /* max number of elements in the tree */
|
21530 | this.max_length = max_length; /* max bit length for the codes */
|
21531 |
|
21532 | // show if `static_tree` has data or dummy - needed for monomorphic objects
|
21533 | this.has_stree = static_tree && static_tree.length;
|
21534 | };
|
21535 |
|
21536 |
|
21537 | var static_l_desc;
|
21538 | var static_d_desc;
|
21539 | var static_bl_desc;
|
21540 |
|
21541 |
|
21542 | var TreeDesc = function(dyn_tree, stat_desc) {
|
21543 | this.dyn_tree = dyn_tree; /* the dynamic tree */
|
21544 | this.max_code = 0; /* largest code with non zero frequency */
|
21545 | this.stat_desc = stat_desc; /* the corresponding static tree */
|
21546 | };
|
21547 |
|
21548 |
|
21549 |
|
21550 | function d_code(dist) {
|
21551 | return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
|
21552 | }
|
21553 |
|
21554 |
|
21555 | /* ===========================================================================
|
21556 | * Output a short LSB first on the stream.
|
21557 | * IN assertion: there is enough room in pendingBuf.
|
21558 | */
|
21559 | function put_short (s, w) {
|
21560 | // put_byte(s, (uch)((w) & 0xff));
|
21561 | // put_byte(s, (uch)((ush)(w) >> 8));
|
21562 | s.pending_buf[s.pending++] = (w) & 0xff;
|
21563 | s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
|
21564 | }
|
21565 |
|
21566 |
|
21567 | /* ===========================================================================
|
21568 | * Send a value on a given number of bits.
|
21569 | * IN assertion: length <= 16 and value fits in length bits.
|
21570 | */
|
21571 | function send_bits(s, value, length) {
|
21572 | if (s.bi_valid > (Buf_size - length)) {
|
21573 | s.bi_buf |= (value << s.bi_valid) & 0xffff;
|
21574 | put_short(s, s.bi_buf);
|
21575 | s.bi_buf = value >> (Buf_size - s.bi_valid);
|
21576 | s.bi_valid += length - Buf_size;
|
21577 | } else {
|
21578 | s.bi_buf |= (value << s.bi_valid) & 0xffff;
|
21579 | s.bi_valid += length;
|
21580 | }
|
21581 | }
|
21582 |
|
21583 |
|
21584 | function send_code(s, c, tree) {
|
21585 | send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
|
21586 | }
|
21587 |
|
21588 |
|
21589 | /* ===========================================================================
|
21590 | * Reverse the first len bits of a code, using straightforward code (a faster
|
21591 | * method would use a table)
|
21592 | * IN assertion: 1 <= len <= 15
|
21593 | */
|
21594 | function bi_reverse(code, len) {
|
21595 | var res = 0;
|
21596 | do {
|
21597 | res |= code & 1;
|
21598 | code >>>= 1;
|
21599 | res <<= 1;
|
21600 | } while (--len > 0);
|
21601 | return res >>> 1;
|
21602 | }
|
21603 |
|
21604 |
|
21605 | /* ===========================================================================
|
21606 | * Flush the bit buffer, keeping at most 7 bits in it.
|
21607 | */
|
21608 | function bi_flush(s) {
|
21609 | if (s.bi_valid === 16) {
|
21610 | put_short(s, s.bi_buf);
|
21611 | s.bi_buf = 0;
|
21612 | s.bi_valid = 0;
|
21613 |
|
21614 | } else if (s.bi_valid >= 8) {
|
21615 | s.pending_buf[s.pending++] = s.bi_buf & 0xff;
|
21616 | s.bi_buf >>= 8;
|
21617 | s.bi_valid -= 8;
|
21618 | }
|
21619 | }
|
21620 |
|
21621 |
|
21622 | /* ===========================================================================
|
21623 | * Compute the optimal bit lengths for a tree and update the total bit length
|
21624 | * for the current block.
|
21625 | * IN assertion: the fields freq and dad are set, heap[heap_max] and
|
21626 | * above are the tree nodes sorted by increasing frequency.
|
21627 | * OUT assertions: the field len is set to the optimal bit length, the
|
21628 | * array bl_count contains the frequencies for each bit length.
|
21629 | * The length opt_len is updated; static_len is also updated if stree is
|
21630 | * not null.
|
21631 | */
|
21632 | function gen_bitlen(s, desc)
|
21633 | // deflate_state *s;
|
21634 | // tree_desc *desc; /* the tree descriptor */
|
21635 | {
|
21636 | var tree = desc.dyn_tree;
|
21637 | var max_code = desc.max_code;
|
21638 | var stree = desc.stat_desc.static_tree;
|
21639 | var has_stree = desc.stat_desc.has_stree;
|
21640 | var extra = desc.stat_desc.extra_bits;
|
21641 | var base = desc.stat_desc.extra_base;
|
21642 | var max_length = desc.stat_desc.max_length;
|
21643 | var h; /* heap index */
|
21644 | var n, m; /* iterate over the tree elements */
|
21645 | var bits; /* bit length */
|
21646 | var xbits; /* extra bits */
|
21647 | var f; /* frequency */
|
21648 | var overflow = 0; /* number of elements with bit length too large */
|
21649 |
|
21650 | for (bits = 0; bits <= MAX_BITS; bits++) {
|
21651 | s.bl_count[bits] = 0;
|
21652 | }
|
21653 |
|
21654 | /* In a first pass, compute the optimal bit lengths (which may
|
21655 | * overflow in the case of the bit length tree).
|
21656 | */
|
21657 | tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
|
21658 |
|
21659 | for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
|
21660 | n = s.heap[h];
|
21661 | bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
|
21662 | if (bits > max_length) {
|
21663 | bits = max_length;
|
21664 | overflow++;
|
21665 | }
|
21666 | tree[n*2 + 1]/*.Len*/ = bits;
|
21667 | /* We overwrite tree[n].Dad which is no longer needed */
|
21668 |
|
21669 | if (n > max_code) { continue; } /* not a leaf node */
|
21670 |
|
21671 | s.bl_count[bits]++;
|
21672 | xbits = 0;
|
21673 | if (n >= base) {
|
21674 | xbits = extra[n-base];
|
21675 | }
|
21676 | f = tree[n * 2]/*.Freq*/;
|
21677 | s.opt_len += f * (bits + xbits);
|
21678 | if (has_stree) {
|
21679 | s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
|
21680 | }
|
21681 | }
|
21682 | if (overflow === 0) { return; }
|
21683 |
|
21684 | // Trace((stderr,"\nbit length overflow\n"));
|
21685 | /* This happens for example on obj2 and pic of the Calgary corpus */
|
21686 |
|
21687 | /* Find the first bit length which could increase: */
|
21688 | do {
|
21689 | bits = max_length-1;
|
21690 | while (s.bl_count[bits] === 0) { bits--; }
|
21691 | s.bl_count[bits]--; /* move one leaf down the tree */
|
21692 | s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
|
21693 | s.bl_count[max_length]--;
|
21694 | /* The brother of the overflow item also moves one step up,
|
21695 | * but this does not affect bl_count[max_length]
|
21696 | */
|
21697 | overflow -= 2;
|
21698 | } while (overflow > 0);
|
21699 |
|
21700 | /* Now recompute all bit lengths, scanning in increasing frequency.
|
21701 | * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
|
21702 | * lengths instead of fixing only the wrong ones. This idea is taken
|
21703 | * from 'ar' written by Haruhiko Okumura.)
|
21704 | */
|
21705 | for (bits = max_length; bits !== 0; bits--) {
|
21706 | n = s.bl_count[bits];
|
21707 | while (n !== 0) {
|
21708 | m = s.heap[--h];
|
21709 | if (m > max_code) { continue; }
|
21710 | if (tree[m*2 + 1]/*.Len*/ !== bits) {
|
21711 | // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
|
21712 | s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
|
21713 | tree[m*2 + 1]/*.Len*/ = bits;
|
21714 | }
|
21715 | n--;
|
21716 | }
|
21717 | }
|
21718 | }
|
21719 |
|
21720 |
|
21721 | /* ===========================================================================
|
21722 | * Generate the codes for a given tree and bit counts (which need not be
|
21723 | * optimal).
|
21724 | * IN assertion: the array bl_count contains the bit length statistics for
|
21725 | * the given tree and the field len is set for all tree elements.
|
21726 | * OUT assertion: the field code is set for all tree elements of non
|
21727 | * zero code length.
|
21728 | */
|
21729 | function gen_codes(tree, max_code, bl_count)
|
21730 | // ct_data *tree; /* the tree to decorate */
|
21731 | // int max_code; /* largest code with non zero frequency */
|
21732 | // ushf *bl_count; /* number of codes at each bit length */
|
21733 | {
|
21734 | var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
|
21735 | var code = 0; /* running code value */
|
21736 | var bits; /* bit index */
|
21737 | var n; /* code index */
|
21738 |
|
21739 | /* The distribution counts are first used to generate the code values
|
21740 | * without bit reversal.
|
21741 | */
|
21742 | for (bits = 1; bits <= MAX_BITS; bits++) {
|
21743 | next_code[bits] = code = (code + bl_count[bits-1]) << 1;
|
21744 | }
|
21745 | /* Check that the bit counts in bl_count are consistent. The last code
|
21746 | * must be all ones.
|
21747 | */
|
21748 | //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
|
21749 | // "inconsistent bit counts");
|
21750 | //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
|
21751 |
|
21752 | for (n = 0; n <= max_code; n++) {
|
21753 | var len = tree[n*2 + 1]/*.Len*/;
|
21754 | if (len === 0) { continue; }
|
21755 | /* Now reverse the bits */
|
21756 | tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
|
21757 |
|
21758 | //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
|
21759 | // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
|
21760 | }
|
21761 | }
|
21762 |
|
21763 |
|
21764 | /* ===========================================================================
|
21765 | * Initialize the various 'constant' tables.
|
21766 | */
|
21767 | function tr_static_init() {
|
21768 | var n; /* iterates over tree elements */
|
21769 | var bits; /* bit counter */
|
21770 | var length; /* length value */
|
21771 | var code; /* code value */
|
21772 | var dist; /* distance index */
|
21773 | var bl_count = new Array(MAX_BITS+1);
|
21774 | /* number of codes at each bit length for an optimal tree */
|
21775 |
|
21776 | // do check in _tr_init()
|
21777 | //if (static_init_done) return;
|
21778 |
|
21779 | /* For some embedded targets, global variables are not initialized: */
|
21780 | /*#ifdef NO_INIT_GLOBAL_POINTERS
|
21781 | static_l_desc.static_tree = static_ltree;
|
21782 | static_l_desc.extra_bits = extra_lbits;
|
21783 | static_d_desc.static_tree = static_dtree;
|
21784 | static_d_desc.extra_bits = extra_dbits;
|
21785 | static_bl_desc.extra_bits = extra_blbits;
|
21786 | #endif*/
|
21787 |
|
21788 | /* Initialize the mapping length (0..255) -> length code (0..28) */
|
21789 | length = 0;
|
21790 | for (code = 0; code < LENGTH_CODES-1; code++) {
|
21791 | base_length[code] = length;
|
21792 | for (n = 0; n < (1<<extra_lbits[code]); n++) {
|
21793 | _length_code[length++] = code;
|
21794 | }
|
21795 | }
|
21796 | //Assert (length == 256, "tr_static_init: length != 256");
|
21797 | /* Note that the length 255 (match length 258) can be represented
|
21798 | * in two different ways: code 284 + 5 bits or code 285, so we
|
21799 | * overwrite length_code[255] to use the best encoding:
|
21800 | */
|
21801 | _length_code[length-1] = code;
|
21802 |
|
21803 | /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
|
21804 | dist = 0;
|
21805 | for (code = 0 ; code < 16; code++) {
|
21806 | base_dist[code] = dist;
|
21807 | for (n = 0; n < (1<<extra_dbits[code]); n++) {
|
21808 | _dist_code[dist++] = code;
|
21809 | }
|
21810 | }
|
21811 | //Assert (dist == 256, "tr_static_init: dist != 256");
|
21812 | dist >>= 7; /* from now on, all distances are divided by 128 */
|
21813 | for (; code < D_CODES; code++) {
|
21814 | base_dist[code] = dist << 7;
|
21815 | for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
|
21816 | _dist_code[256 + dist++] = code;
|
21817 | }
|
21818 | }
|
21819 | //Assert (dist == 256, "tr_static_init: 256+dist != 512");
|
21820 |
|
21821 | /* Construct the codes of the static literal tree */
|
21822 | for (bits = 0; bits <= MAX_BITS; bits++) {
|
21823 | bl_count[bits] = 0;
|
21824 | }
|
21825 |
|
21826 | n = 0;
|
21827 | while (n <= 143) {
|
21828 | static_ltree[n*2 + 1]/*.Len*/ = 8;
|
21829 | n++;
|
21830 | bl_count[8]++;
|
21831 | }
|
21832 | while (n <= 255) {
|
21833 | static_ltree[n*2 + 1]/*.Len*/ = 9;
|
21834 | n++;
|
21835 | bl_count[9]++;
|
21836 | }
|
21837 | while (n <= 279) {
|
21838 | static_ltree[n*2 + 1]/*.Len*/ = 7;
|
21839 | n++;
|
21840 | bl_count[7]++;
|
21841 | }
|
21842 | while (n <= 287) {
|
21843 | static_ltree[n*2 + 1]/*.Len*/ = 8;
|
21844 | n++;
|
21845 | bl_count[8]++;
|
21846 | }
|
21847 | /* Codes 286 and 287 do not exist, but we must include them in the
|
21848 | * tree construction to get a canonical Huffman tree (longest code
|
21849 | * all ones)
|
21850 | */
|
21851 | gen_codes(static_ltree, L_CODES+1, bl_count);
|
21852 |
|
21853 | /* The static distance tree is trivial: */
|
21854 | for (n = 0; n < D_CODES; n++) {
|
21855 | static_dtree[n*2 + 1]/*.Len*/ = 5;
|
21856 | static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
|
21857 | }
|
21858 |
|
21859 | // Now data ready and we can init static trees
|
21860 | static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
|
21861 | static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
|
21862 | static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
|
21863 |
|
21864 | //static_init_done = true;
|
21865 | }
|
21866 |
|
21867 |
|
21868 | /* ===========================================================================
|
21869 | * Initialize a new block.
|
21870 | */
|
21871 | function init_block(s) {
|
21872 | var n; /* iterates over tree elements */
|
21873 |
|
21874 | /* Initialize the trees. */
|
21875 | for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
|
21876 | for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
|
21877 | for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
|
21878 |
|
21879 | s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
|
21880 | s.opt_len = s.static_len = 0;
|
21881 | s.last_lit = s.matches = 0;
|
21882 | }
|
21883 |
|
21884 |
|
21885 | /* ===========================================================================
|
21886 | * Flush the bit buffer and align the output on a byte boundary
|
21887 | */
|
21888 | function bi_windup(s)
|
21889 | {
|
21890 | if (s.bi_valid > 8) {
|
21891 | put_short(s, s.bi_buf);
|
21892 | } else if (s.bi_valid > 0) {
|
21893 | //put_byte(s, (Byte)s->bi_buf);
|
21894 | s.pending_buf[s.pending++] = s.bi_buf;
|
21895 | }
|
21896 | s.bi_buf = 0;
|
21897 | s.bi_valid = 0;
|
21898 | }
|
21899 |
|
21900 | /* ===========================================================================
|
21901 | * Copy a stored block, storing first the length and its
|
21902 | * one's complement if requested.
|
21903 | */
|
21904 | function copy_block(s, buf, len, header)
|
21905 | //DeflateState *s;
|
21906 | //charf *buf; /* the input data */
|
21907 | //unsigned len; /* its length */
|
21908 | //int header; /* true if block header must be written */
|
21909 | {
|
21910 | bi_windup(s); /* align on byte boundary */
|
21911 |
|
21912 | if (header) {
|
21913 | put_short(s, len);
|
21914 | put_short(s, ~len);
|
21915 | }
|
21916 | // while (len--) {
|
21917 | // put_byte(s, *buf++);
|
21918 | // }
|
21919 | utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
|
21920 | s.pending += len;
|
21921 | }
|
21922 |
|
21923 | /* ===========================================================================
|
21924 | * Compares to subtrees, using the tree depth as tie breaker when
|
21925 | * the subtrees have equal frequency. This minimizes the worst case length.
|
21926 | */
|
21927 | function smaller(tree, n, m, depth) {
|
21928 | var _n2 = n*2;
|
21929 | var _m2 = m*2;
|
21930 | return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
|
21931 | (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
|
21932 | }
|
21933 |
|
21934 | /* ===========================================================================
|
21935 | * Restore the heap property by moving down the tree starting at node k,
|
21936 | * exchanging a node with the smallest of its two sons if necessary, stopping
|
21937 | * when the heap property is re-established (each father smaller than its
|
21938 | * two sons).
|
21939 | */
|
21940 | function pqdownheap(s, tree, k)
|
21941 | // deflate_state *s;
|
21942 | // ct_data *tree; /* the tree to restore */
|
21943 | // int k; /* node to move down */
|
21944 | {
|
21945 | var v = s.heap[k];
|
21946 | var j = k << 1; /* left son of k */
|
21947 | while (j <= s.heap_len) {
|
21948 | /* Set j to the smallest of the two sons: */
|
21949 | if (j < s.heap_len &&
|
21950 | smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
|
21951 | j++;
|
21952 | }
|
21953 | /* Exit if v is smaller than both sons */
|
21954 | if (smaller(tree, v, s.heap[j], s.depth)) { break; }
|
21955 |
|
21956 | /* Exchange v with the smallest son */
|
21957 | s.heap[k] = s.heap[j];
|
21958 | k = j;
|
21959 |
|
21960 | /* And continue down the tree, setting j to the left son of k */
|
21961 | j <<= 1;
|
21962 | }
|
21963 | s.heap[k] = v;
|
21964 | }
|
21965 |
|
21966 |
|
21967 | // inlined manually
|
21968 | // var SMALLEST = 1;
|
21969 |
|
21970 | /* ===========================================================================
|
21971 | * Send the block data compressed using the given Huffman trees
|
21972 | */
|
21973 | function compress_block(s, ltree, dtree)
|
21974 | // deflate_state *s;
|
21975 | // const ct_data *ltree; /* literal tree */
|
21976 | // const ct_data *dtree; /* distance tree */
|
21977 | {
|
21978 | var dist; /* distance of matched string */
|
21979 | var lc; /* match length or unmatched char (if dist == 0) */
|
21980 | var lx = 0; /* running index in l_buf */
|
21981 | var code; /* the code to send */
|
21982 | var extra; /* number of extra bits to send */
|
21983 |
|
21984 | if (s.last_lit !== 0) {
|
21985 | do {
|
21986 | dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
|
21987 | lc = s.pending_buf[s.l_buf + lx];
|
21988 | lx++;
|
21989 |
|
21990 | if (dist === 0) {
|
21991 | send_code(s, lc, ltree); /* send a literal byte */
|
21992 | //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
|
21993 | } else {
|
21994 | /* Here, lc is the match length - MIN_MATCH */
|
21995 | code = _length_code[lc];
|
21996 | send_code(s, code+LITERALS+1, ltree); /* send the length code */
|
21997 | extra = extra_lbits[code];
|
21998 | if (extra !== 0) {
|
21999 | lc -= base_length[code];
|
22000 | send_bits(s, lc, extra); /* send the extra length bits */
|
22001 | }
|
22002 | dist--; /* dist is now the match distance - 1 */
|
22003 | code = d_code(dist);
|
22004 | //Assert (code < D_CODES, "bad d_code");
|
22005 |
|
22006 | send_code(s, code, dtree); /* send the distance code */
|
22007 | extra = extra_dbits[code];
|
22008 | if (extra !== 0) {
|
22009 | dist -= base_dist[code];
|
22010 | send_bits(s, dist, extra); /* send the extra distance bits */
|
22011 | }
|
22012 | } /* literal or match pair ? */
|
22013 |
|
22014 | /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
|
22015 | //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
|
22016 | // "pendingBuf overflow");
|
22017 |
|
22018 | } while (lx < s.last_lit);
|
22019 | }
|
22020 |
|
22021 | send_code(s, END_BLOCK, ltree);
|
22022 | }
|
22023 |
|
22024 |
|
22025 | /* ===========================================================================
|
22026 | * Construct one Huffman tree and assigns the code bit strings and lengths.
|
22027 | * Update the total bit length for the current block.
|
22028 | * IN assertion: the field freq is set for all tree elements.
|
22029 | * OUT assertions: the fields len and code are set to the optimal bit length
|
22030 | * and corresponding code. The length opt_len is updated; static_len is
|
22031 | * also updated if stree is not null. The field max_code is set.
|
22032 | */
|
22033 | function build_tree(s, desc)
|
22034 | // deflate_state *s;
|
22035 | // tree_desc *desc; /* the tree descriptor */
|
22036 | {
|
22037 | var tree = desc.dyn_tree;
|
22038 | var stree = desc.stat_desc.static_tree;
|
22039 | var has_stree = desc.stat_desc.has_stree;
|
22040 | var elems = desc.stat_desc.elems;
|
22041 | var n, m; /* iterate over heap elements */
|
22042 | var max_code = -1; /* largest code with non zero frequency */
|
22043 | var node; /* new node being created */
|
22044 |
|
22045 | /* Construct the initial heap, with least frequent element in
|
22046 | * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
|
22047 | * heap[0] is not used.
|
22048 | */
|
22049 | s.heap_len = 0;
|
22050 | s.heap_max = HEAP_SIZE;
|
22051 |
|
22052 | for (n = 0; n < elems; n++) {
|
22053 | if (tree[n * 2]/*.Freq*/ !== 0) {
|
22054 | s.heap[++s.heap_len] = max_code = n;
|
22055 | s.depth[n] = 0;
|
22056 |
|
22057 | } else {
|
22058 | tree[n*2 + 1]/*.Len*/ = 0;
|
22059 | }
|
22060 | }
|
22061 |
|
22062 | /* The pkzip format requires that at least one distance code exists,
|
22063 | * and that at least one bit should be sent even if there is only one
|
22064 | * possible code. So to avoid special checks later on we force at least
|
22065 | * two codes of non zero frequency.
|
22066 | */
|
22067 | while (s.heap_len < 2) {
|
22068 | node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
|
22069 | tree[node * 2]/*.Freq*/ = 1;
|
22070 | s.depth[node] = 0;
|
22071 | s.opt_len--;
|
22072 |
|
22073 | if (has_stree) {
|
22074 | s.static_len -= stree[node*2 + 1]/*.Len*/;
|
22075 | }
|
22076 | /* node is 0 or 1 so it does not have extra bits */
|
22077 | }
|
22078 | desc.max_code = max_code;
|
22079 |
|
22080 | /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
|
22081 | * establish sub-heaps of increasing lengths:
|
22082 | */
|
22083 | for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
|
22084 |
|
22085 | /* Construct the Huffman tree by repeatedly combining the least two
|
22086 | * frequent nodes.
|
22087 | */
|
22088 | node = elems; /* next internal node of the tree */
|
22089 | do {
|
22090 | //pqremove(s, tree, n); /* n = node of least frequency */
|
22091 | /*** pqremove ***/
|
22092 | n = s.heap[1/*SMALLEST*/];
|
22093 | s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
|
22094 | pqdownheap(s, tree, 1/*SMALLEST*/);
|
22095 | /***/
|
22096 |
|
22097 | m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
|
22098 |
|
22099 | s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
|
22100 | s.heap[--s.heap_max] = m;
|
22101 |
|
22102 | /* Create a new node father of n and m */
|
22103 | tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
|
22104 | s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
|
22105 | tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
|
22106 |
|
22107 | /* and insert the new node in the heap */
|
22108 | s.heap[1/*SMALLEST*/] = node++;
|
22109 | pqdownheap(s, tree, 1/*SMALLEST*/);
|
22110 |
|
22111 | } while (s.heap_len >= 2);
|
22112 |
|
22113 | s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
|
22114 |
|
22115 | /* At this point, the fields freq and dad are set. We can now
|
22116 | * generate the bit lengths.
|
22117 | */
|
22118 | gen_bitlen(s, desc);
|
22119 |
|
22120 | /* The field len is now set, we can generate the bit codes */
|
22121 | gen_codes(tree, max_code, s.bl_count);
|
22122 | }
|
22123 |
|
22124 |
|
22125 | /* ===========================================================================
|
22126 | * Scan a literal or distance tree to determine the frequencies of the codes
|
22127 | * in the bit length tree.
|
22128 | */
|
22129 | function scan_tree(s, tree, max_code)
|
22130 | // deflate_state *s;
|
22131 | // ct_data *tree; /* the tree to be scanned */
|
22132 | // int max_code; /* and its largest code of non zero frequency */
|
22133 | {
|
22134 | var n; /* iterates over all tree elements */
|
22135 | var prevlen = -1; /* last emitted length */
|
22136 | var curlen; /* length of current code */
|
22137 |
|
22138 | var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
|
22139 |
|
22140 | var count = 0; /* repeat count of the current code */
|
22141 | var max_count = 7; /* max repeat count */
|
22142 | var min_count = 4; /* min repeat count */
|
22143 |
|
22144 | if (nextlen === 0) {
|
22145 | max_count = 138;
|
22146 | min_count = 3;
|
22147 | }
|
22148 | tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
|
22149 |
|
22150 | for (n = 0; n <= max_code; n++) {
|
22151 | curlen = nextlen;
|
22152 | nextlen = tree[(n+1)*2 + 1]/*.Len*/;
|
22153 |
|
22154 | if (++count < max_count && curlen === nextlen) {
|
22155 | continue;
|
22156 |
|
22157 | } else if (count < min_count) {
|
22158 | s.bl_tree[curlen * 2]/*.Freq*/ += count;
|
22159 |
|
22160 | } else if (curlen !== 0) {
|
22161 |
|
22162 | if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
|
22163 | s.bl_tree[REP_3_6*2]/*.Freq*/++;
|
22164 |
|
22165 | } else if (count <= 10) {
|
22166 | s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
|
22167 |
|
22168 | } else {
|
22169 | s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
|
22170 | }
|
22171 |
|
22172 | count = 0;
|
22173 | prevlen = curlen;
|
22174 |
|
22175 | if (nextlen === 0) {
|
22176 | max_count = 138;
|
22177 | min_count = 3;
|
22178 |
|
22179 | } else if (curlen === nextlen) {
|
22180 | max_count = 6;
|
22181 | min_count = 3;
|
22182 |
|
22183 | } else {
|
22184 | max_count = 7;
|
22185 | min_count = 4;
|
22186 | }
|
22187 | }
|
22188 | }
|
22189 |
|
22190 |
|
22191 | /* ===========================================================================
|
22192 | * Send a literal or distance tree in compressed form, using the codes in
|
22193 | * bl_tree.
|
22194 | */
|
22195 | function send_tree(s, tree, max_code)
|
22196 | // deflate_state *s;
|
22197 | // ct_data *tree; /* the tree to be scanned */
|
22198 | // int max_code; /* and its largest code of non zero frequency */
|
22199 | {
|
22200 | var n; /* iterates over all tree elements */
|
22201 | var prevlen = -1; /* last emitted length */
|
22202 | var curlen; /* length of current code */
|
22203 |
|
22204 | var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
|
22205 |
|
22206 | var count = 0; /* repeat count of the current code */
|
22207 | var max_count = 7; /* max repeat count */
|
22208 | var min_count = 4; /* min repeat count */
|
22209 |
|
22210 | /* tree[max_code+1].Len = -1; */ /* guard already set */
|
22211 | if (nextlen === 0) {
|
22212 | max_count = 138;
|
22213 | min_count = 3;
|
22214 | }
|
22215 |
|
22216 | for (n = 0; n <= max_code; n++) {
|
22217 | curlen = nextlen;
|
22218 | nextlen = tree[(n+1)*2 + 1]/*.Len*/;
|
22219 |
|
22220 | if (++count < max_count && curlen === nextlen) {
|
22221 | continue;
|
22222 |
|
22223 | } else if (count < min_count) {
|
22224 | do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
|
22225 |
|
22226 | } else if (curlen !== 0) {
|
22227 | if (curlen !== prevlen) {
|
22228 | send_code(s, curlen, s.bl_tree);
|
22229 | count--;
|
22230 | }
|
22231 | //Assert(count >= 3 && count <= 6, " 3_6?");
|
22232 | send_code(s, REP_3_6, s.bl_tree);
|
22233 | send_bits(s, count-3, 2);
|
22234 |
|
22235 | } else if (count <= 10) {
|
22236 | send_code(s, REPZ_3_10, s.bl_tree);
|
22237 | send_bits(s, count-3, 3);
|
22238 |
|
22239 | } else {
|
22240 | send_code(s, REPZ_11_138, s.bl_tree);
|
22241 | send_bits(s, count-11, 7);
|
22242 | }
|
22243 |
|
22244 | count = 0;
|
22245 | prevlen = curlen;
|
22246 | if (nextlen === 0) {
|
22247 | max_count = 138;
|
22248 | min_count = 3;
|
22249 |
|
22250 | } else if (curlen === nextlen) {
|
22251 | max_count = 6;
|
22252 | min_count = 3;
|
22253 |
|
22254 | } else {
|
22255 | max_count = 7;
|
22256 | min_count = 4;
|
22257 | }
|
22258 | }
|
22259 | }
|
22260 |
|
22261 |
|
22262 | /* ===========================================================================
|
22263 | * Construct the Huffman tree for the bit lengths and return the index in
|
22264 | * bl_order of the last bit length code to send.
|
22265 | */
|
22266 | function build_bl_tree(s) {
|
22267 | var max_blindex; /* index of last bit length code of non zero freq */
|
22268 |
|
22269 | /* Determine the bit length frequencies for literal and distance trees */
|
22270 | scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
|
22271 | scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
|
22272 |
|
22273 | /* Build the bit length tree: */
|
22274 | build_tree(s, s.bl_desc);
|
22275 | /* opt_len now includes the length of the tree representations, except
|
22276 | * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
|
22277 | */
|
22278 |
|
22279 | /* Determine the number of bit length codes to send. The pkzip format
|
22280 | * requires that at least 4 bit length codes be sent. (appnote.txt says
|
22281 | * 3 but the actual value used is 4.)
|
22282 | */
|
22283 | for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
|
22284 | if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
|
22285 | break;
|
22286 | }
|
22287 | }
|
22288 | /* Update opt_len to include the bit length tree and counts */
|
22289 | s.opt_len += 3*(max_blindex+1) + 5+5+4;
|
22290 | //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
|
22291 | // s->opt_len, s->static_len));
|
22292 |
|
22293 | return max_blindex;
|
22294 | }
|
22295 |
|
22296 |
|
22297 | /* ===========================================================================
|
22298 | * Send the header for a block using dynamic Huffman trees: the counts, the
|
22299 | * lengths of the bit length codes, the literal tree and the distance tree.
|
22300 | * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
|
22301 | */
|
22302 | function send_all_trees(s, lcodes, dcodes, blcodes)
|
22303 | // deflate_state *s;
|
22304 | // int lcodes, dcodes, blcodes; /* number of codes for each tree */
|
22305 | {
|
22306 | var rank; /* index in bl_order */
|
22307 |
|
22308 | //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
|
22309 | //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
|
22310 | // "too many codes");
|
22311 | //Tracev((stderr, "\nbl counts: "));
|
22312 | send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
|
22313 | send_bits(s, dcodes-1, 5);
|
22314 | send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
|
22315 | for (rank = 0; rank < blcodes; rank++) {
|
22316 | //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
|
22317 | send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
|
22318 | }
|
22319 | //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
|
22320 |
|
22321 | send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
|
22322 | //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
|
22323 |
|
22324 | send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
|
22325 | //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
|
22326 | }
|
22327 |
|
22328 |
|
22329 | /* ===========================================================================
|
22330 | * Check if the data type is TEXT or BINARY, using the following algorithm:
|
22331 | * - TEXT if the two conditions below are satisfied:
|
22332 | * a) There are no non-portable control characters belonging to the
|
22333 | * "black list" (0..6, 14..25, 28..31).
|
22334 | * b) There is at least one printable character belonging to the
|
22335 | * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
|
22336 | * - BINARY otherwise.
|
22337 | * - The following partially-portable control characters form a
|
22338 | * "gray list" that is ignored in this detection algorithm:
|
22339 | * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
|
22340 | * IN assertion: the fields Freq of dyn_ltree are set.
|
22341 | */
|
22342 | function detect_data_type(s) {
|
22343 | /* black_mask is the bit mask of black-listed bytes
|
22344 | * set bits 0..6, 14..25, and 28..31
|
22345 | * 0xf3ffc07f = binary 11110011111111111100000001111111
|
22346 | */
|
22347 | var black_mask = 0xf3ffc07f;
|
22348 | var n;
|
22349 |
|
22350 | /* Check for non-textual ("black-listed") bytes. */
|
22351 | for (n = 0; n <= 31; n++, black_mask >>>= 1) {
|
22352 | if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
|
22353 | return Z_BINARY;
|
22354 | }
|
22355 | }
|
22356 |
|
22357 | /* Check for textual ("white-listed") bytes. */
|
22358 | if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
|
22359 | s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
|
22360 | return Z_TEXT;
|
22361 | }
|
22362 | for (n = 32; n < LITERALS; n++) {
|
22363 | if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
|
22364 | return Z_TEXT;
|
22365 | }
|
22366 | }
|
22367 |
|
22368 | /* There are no "black-listed" or "white-listed" bytes:
|
22369 | * this stream either is empty or has tolerated ("gray-listed") bytes only.
|
22370 | */
|
22371 | return Z_BINARY;
|
22372 | }
|
22373 |
|
22374 |
|
22375 | var static_init_done = false;
|
22376 |
|
22377 | /* ===========================================================================
|
22378 | * Initialize the tree data structures for a new zlib stream.
|
22379 | */
|
22380 | function _tr_init(s)
|
22381 | {
|
22382 |
|
22383 | if (!static_init_done) {
|
22384 | tr_static_init();
|
22385 | static_init_done = true;
|
22386 | }
|
22387 |
|
22388 | s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
|
22389 | s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
|
22390 | s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
|
22391 |
|
22392 | s.bi_buf = 0;
|
22393 | s.bi_valid = 0;
|
22394 |
|
22395 | /* Initialize the first block of the first file: */
|
22396 | init_block(s);
|
22397 | }
|
22398 |
|
22399 |
|
22400 | /* ===========================================================================
|
22401 | * Send a stored block
|
22402 | */
|
22403 | function _tr_stored_block(s, buf, stored_len, last)
|
22404 | //DeflateState *s;
|
22405 | //charf *buf; /* input block */
|
22406 | //ulg stored_len; /* length of input block */
|
22407 | //int last; /* one if this is the last block for a file */
|
22408 | {
|
22409 | send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
|
22410 | copy_block(s, buf, stored_len, true); /* with header */
|
22411 | }
|
22412 |
|
22413 |
|
22414 | /* ===========================================================================
|
22415 | * Send one empty static block to give enough lookahead for inflate.
|
22416 | * This takes 10 bits, of which 7 may remain in the bit buffer.
|
22417 | */
|
22418 | function _tr_align(s) {
|
22419 | send_bits(s, STATIC_TREES<<1, 3);
|
22420 | send_code(s, END_BLOCK, static_ltree);
|
22421 | bi_flush(s);
|
22422 | }
|
22423 |
|
22424 |
|
22425 | /* ===========================================================================
|
22426 | * Determine the best encoding for the current block: dynamic trees, static
|
22427 | * trees or store, and output the encoded block to the zip file.
|
22428 | */
|
22429 | function _tr_flush_block(s, buf, stored_len, last)
|
22430 | //DeflateState *s;
|
22431 | //charf *buf; /* input block, or NULL if too old */
|
22432 | //ulg stored_len; /* length of input block */
|
22433 | //int last; /* one if this is the last block for a file */
|
22434 | {
|
22435 | var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
|
22436 | var max_blindex = 0; /* index of last bit length code of non zero freq */
|
22437 |
|
22438 | /* Build the Huffman trees unless a stored block is forced */
|
22439 | if (s.level > 0) {
|
22440 |
|
22441 | /* Check if the file is binary or text */
|
22442 | if (s.strm.data_type === Z_UNKNOWN) {
|
22443 | s.strm.data_type = detect_data_type(s);
|
22444 | }
|
22445 |
|
22446 | /* Construct the literal and distance trees */
|
22447 | build_tree(s, s.l_desc);
|
22448 | // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
|
22449 | // s->static_len));
|
22450 |
|
22451 | build_tree(s, s.d_desc);
|
22452 | // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
|
22453 | // s->static_len));
|
22454 | /* At this point, opt_len and static_len are the total bit lengths of
|
22455 | * the compressed block data, excluding the tree representations.
|
22456 | */
|
22457 |
|
22458 | /* Build the bit length tree for the above two trees, and get the index
|
22459 | * in bl_order of the last bit length code to send.
|
22460 | */
|
22461 | max_blindex = build_bl_tree(s);
|
22462 |
|
22463 | /* Determine the best encoding. Compute the block lengths in bytes. */
|
22464 | opt_lenb = (s.opt_len+3+7) >>> 3;
|
22465 | static_lenb = (s.static_len+3+7) >>> 3;
|
22466 |
|
22467 | // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
|
22468 | // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
|
22469 | // s->last_lit));
|
22470 |
|
22471 | if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
|
22472 |
|
22473 | } else {
|
22474 | // Assert(buf != (char*)0, "lost buf");
|
22475 | opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
|
22476 | }
|
22477 |
|
22478 | if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
|
22479 | /* 4: two words for the lengths */
|
22480 |
|
22481 | /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
|
22482 | * Otherwise we can't have processed more than WSIZE input bytes since
|
22483 | * the last block flush, because compression would have been
|
22484 | * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
|
22485 | * transform a block into a stored block.
|
22486 | */
|
22487 | _tr_stored_block(s, buf, stored_len, last);
|
22488 |
|
22489 | } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
|
22490 |
|
22491 | send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
|
22492 | compress_block(s, static_ltree, static_dtree);
|
22493 |
|
22494 | } else {
|
22495 | send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
|
22496 | send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
|
22497 | compress_block(s, s.dyn_ltree, s.dyn_dtree);
|
22498 | }
|
22499 | // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
|
22500 | /* The above check is made mod 2^32, for files larger than 512 MB
|
22501 | * and uLong implemented on 32 bits.
|
22502 | */
|
22503 | init_block(s);
|
22504 |
|
22505 | if (last) {
|
22506 | bi_windup(s);
|
22507 | }
|
22508 | // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
|
22509 | // s->compressed_len-7*last));
|
22510 | }
|
22511 |
|
22512 | /* ===========================================================================
|
22513 | * Save the match info and tally the frequency counts. Return true if
|
22514 | * the current block must be flushed.
|
22515 | */
|
22516 | function _tr_tally(s, dist, lc)
|
22517 | // deflate_state *s;
|
22518 | // unsigned dist; /* distance of matched string */
|
22519 | // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
|
22520 | {
|
22521 | //var out_length, in_length, dcode;
|
22522 |
|
22523 | s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
|
22524 | s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
|
22525 |
|
22526 | s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
|
22527 | s.last_lit++;
|
22528 |
|
22529 | if (dist === 0) {
|
22530 | /* lc is the unmatched char */
|
22531 | s.dyn_ltree[lc*2]/*.Freq*/++;
|
22532 | } else {
|
22533 | s.matches++;
|
22534 | /* Here, lc is the match length - MIN_MATCH */
|
22535 | dist--; /* dist = match distance - 1 */
|
22536 | //Assert((ush)dist < (ush)MAX_DIST(s) &&
|
22537 | // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
|
22538 | // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
|
22539 |
|
22540 | s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
|
22541 | s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
|
22542 | }
|
22543 |
|
22544 | // (!) This block is disabled in zlib defailts,
|
22545 | // don't enable it for binary compatibility
|
22546 |
|
22547 | //#ifdef TRUNCATE_BLOCK
|
22548 | // /* Try to guess if it is profitable to stop the current block here */
|
22549 | // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
|
22550 | // /* Compute an upper bound for the compressed length */
|
22551 | // out_length = s.last_lit*8;
|
22552 | // in_length = s.strstart - s.block_start;
|
22553 | //
|
22554 | // for (dcode = 0; dcode < D_CODES; dcode++) {
|
22555 | // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
|
22556 | // }
|
22557 | // out_length >>>= 3;
|
22558 | // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
|
22559 | // // s->last_lit, in_length, out_length,
|
22560 | // // 100L - out_length*100L/in_length));
|
22561 | // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
|
22562 | // return true;
|
22563 | // }
|
22564 | // }
|
22565 | //#endif
|
22566 |
|
22567 | return (s.last_lit === s.lit_bufsize-1);
|
22568 | /* We avoid equality with lit_bufsize because of wraparound at 64K
|
22569 | * on 16 bit machines and because stored blocks are restricted to
|
22570 | * 64K-1 bytes.
|
22571 | */
|
22572 | }
|
22573 |
|
22574 | exports._tr_init = _tr_init;
|
22575 | exports._tr_stored_block = _tr_stored_block;
|
22576 | exports._tr_flush_block = _tr_flush_block;
|
22577 | exports._tr_tally = _tr_tally;
|
22578 | exports._tr_align = _tr_align;
|
22579 |
|
22580 | },{"../utils/common":14}],26:[function(require,module,exports){
|
22581 | 'use strict';
|
22582 |
|
22583 |
|
22584 | function ZStream() {
|
22585 | /* next input byte */
|
22586 | this.input = null; // JS specific, because we have no pointers
|
22587 | this.next_in = 0;
|
22588 | /* number of bytes available at input */
|
22589 | this.avail_in = 0;
|
22590 | /* total number of input bytes read so far */
|
22591 | this.total_in = 0;
|
22592 | /* next output byte should be put there */
|
22593 | this.output = null; // JS specific, because we have no pointers
|
22594 | this.next_out = 0;
|
22595 | /* remaining free space at output */
|
22596 | this.avail_out = 0;
|
22597 | /* total number of bytes output so far */
|
22598 | this.total_out = 0;
|
22599 | /* last error message, NULL if no error */
|
22600 | this.msg = ''/*Z_NULL*/;
|
22601 | /* not visible by applications */
|
22602 | this.state = null;
|
22603 | /* best guess about the data type: binary or text */
|
22604 | this.data_type = 2/*Z_UNKNOWN*/;
|
22605 | /* adler32 value of the uncompressed data */
|
22606 | this.adler = 0;
|
22607 | }
|
22608 |
|
22609 | module.exports = ZStream;
|
22610 |
|
22611 | },{}]},{},[1])(1)
|
22612 | }); |
\ | No newline at end of file |