MCPcopy
hub / github.com/immutable-js/immutable-js / sliceFactory

Function sliceFactory

src/Operations.js:409–504  ·  view source on GitHub ↗
(collection, begin, end, useKeys)

Source from the content-addressed store, hash-verified

407}
408
409export function sliceFactory(collection, begin, end, useKeys) {
410 const originalSize = collection.size;
411
412 if (wholeSlice(begin, end, originalSize)) {
413 return collection;
414 }
415
416 // begin or end can not be resolved if they were provided as negative numbers and
417 // this collection's size is unknown. In that case, cache first so there is
418 // a known size and these do not resolve to NaN.
419 if (typeof originalSize === 'undefined' && (begin < 0 || end < 0)) {
420 return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys);
421 }
422
423 const resolvedBegin = resolveBegin(begin, originalSize);
424 const resolvedEnd = resolveEnd(end, originalSize);
425
426 // Note: resolvedEnd is undefined when the original sequence's length is
427 // unknown and this slice did not supply an end and should contain all
428 // elements after resolvedBegin.
429 // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
430 const resolvedSize = resolvedEnd - resolvedBegin;
431 let sliceSize;
432 if (resolvedSize === resolvedSize) {
433 sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
434 }
435
436 const sliceSeq = makeSequence(collection);
437
438 // If collection.size is undefined, the size of the realized sliceSeq is
439 // unknown at this point unless the number of items to slice is 0
440 sliceSeq.size =
441 sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined;
442
443 if (!useKeys && isSeq(collection) && sliceSize >= 0) {
444 sliceSeq.get = function (index, notSetValue) {
445 index = wrapIndex(this, index);
446 return index >= 0 && index < sliceSize
447 ? collection.get(index + resolvedBegin, notSetValue)
448 : notSetValue;
449 };
450 }
451
452 sliceSeq.__iterateUncached = function (fn, reverse) {
453 if (sliceSize === 0) {
454 return 0;
455 }
456 if (reverse) {
457 return this.cacheResult().__iterate(fn, reverse);
458 }
459 let skipped = 0;
460 let isSkipping = true;
461 let iterations = 0;
462 collection.__iterate((v, k) => {
463 if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
464 iterations++;
465 return (
466 fn(v, useKeys ? k : iterations - 1, this) !== false &&

Callers 1

sliceFunction · 0.90

Calls 14

wholeSliceFunction · 0.90
resolveBeginFunction · 0.90
resolveEndFunction · 0.90
isSeqFunction · 0.90
wrapIndexFunction · 0.90
iteratorDoneFunction · 0.90
iteratorValueFunction · 0.90
makeSequenceFunction · 0.85
nextMethod · 0.80
cacheResultMethod · 0.65
toSeqMethod · 0.65
getMethod · 0.65

Tested by

no test coverage detected