Skip to content

Latest commit

 

History

History
executable file
·
1121 lines (923 loc) · 37.6 KB

vec.api.md

File metadata and controls

executable file
·
1121 lines (923 loc) · 37.6 KB

Vec APIs


Vec.allPairs(source1, source2) ⇒ Vec

Returns a new vector that contains all pairings of elements from the first and second arrays or vectors.

Returns: Vec - The resulting vector of pairs.
Throws:

  • TypeError if either of the input arguments is null or not of type array or vector.
Param Type Description
source1 Array | Vec The first input array or vector.
source2 Array | Vec The second input array or vector.

Example

const source1 = new Vec(1,2,3);
const source2 = new Vec(4,5);
const pairs = Vec.allPairs(source1, source2);
console.log(pairs);
// =>  [ [ 1, 4 ], [ 1, 5 ], [ 2, 4 ], [ 2, 5 ], [ 3, 4 ], [ 3, 5 ] ]

average() ⇒ number|undefined

Returns the average of the elements in the vector.

Returns: number | undefined - The average of the elements in the vector or undefined if the vector is empty.
Example

const oneToTen = Vec.init(10, x => x + 1);
const avg = oneToTen.average();
console.log(avg);
// => 5.5

averageBy(projection) ⇒ number|undefined

Returns the average of the elements generated by applying the function to each element of the vector.

Returns: number | undefined - The computed average or undefined if the source vector is empty.
Throws:

  • TypeError if projection is a generator function or not a function.
Param Type Description
projection function The function to transform the vector elements before averaging.

Example

const vecOfObjs = new Vec({ n: 1 }, { n: 1 }, { n: 1 }, { n: 1 }, { n: -1 }, { n: 1 });
const avgBy = vecOfObjs.averageBy(({ n }) => n);
console.log(avgBy);
// => 0.6666666666666666

binarySearch(item, comparer) ⇒ number

Searches the entire sorted vector for an element using the specified comparer and returns the zero-based index of the element.

Returns: number - The zero-based index of item in the sorted vector, if item is found; otherwise, -1.
Throws:

  • TypeError if the item to search is null or undefined.
Param Type Description
item * The object to locate.
comparer function The function to compare elements of the vector. if not provided, the default comparer will be used.

Example

const randomNums = new Vec(10, 23, 32, 455, 233, 33, 456, 323, 42, 2, 45, 23, 66);
const descendingOrd = (x, y) => x > y ? -1 : x < y ? 1 : 0;
randomNums.sort(descendingOrd); // => [ 456, 455, 323, 233, 66, 45, 42, 33, 32, 23, 23, 10, 2 ]
const descendingIndex = randomNums.binarySearch(33, descendingOrd);
console.log(descendingIndex);
// => 7
const ascendingOrd = (x, y) => x < y ? -1 : x > y ? 1 : 0;
randomNums.sort(ascendingOrd); // => [ 2, 10, 23, 23, 32, 33, 42, 45, 66, 233, 323, 455, 456 ]
const ascendingIndex = randomNums.binarySearch(33); // default comparer is used here and it's the same as ascendingOrd
console.log(ascendingIndex);
// => 5

chunkBySize(chunkSize) ⇒ Vec

Divides the source vector into chunks of size at most chunkSize.

Returns: Vec - The vector divided into chunks.
Throws:

  • TypeError if chunkSize is negative.
Param Type Description
chunkSize number The maximum size of each chunk.

Example

const vec = Vec.init(10, x => x + 1);
const chunks = vec.chunkBySize(3);
console.log(chunks);
// => [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]

copy() ⇒ Vec

Builds a new vector that contains the elements of the source vector.

Returns: Vec - A copy of the source vector.
Example

const sourceVec = Vec.init(5, x => x);
const copyVec = sourceVec.copy();
console.log(copyVec);
// => [ 0, 1, 2, 3, 4 ]

Vec

Vec extends Array and has all the methods of Array.

countBy(projection) ⇒ Vec

Applies a key-generating function to each element of a vector and returns a vector yielding unique keys and their number of occurrences in the original array.

Returns: Vec - The result vector.
Throws:

  • TypeError if struturalEquality parameter is null or undefined; or projection parameter is a generator function or not a function.
Param Type Description
projection function A function transforming each item of the input vector into a key to be compared against the others.
Value object to use as this when executing projection

Example

const countByVec = new Vec(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5);
const counts_1 = countByVec.countBy(x => x);
console.log(counts_1);
// => [ [ 1, 5 ], [ 2, 5 ], [ 3, 3 ], [ 4, 3 ], [ 5, 1 ] ]
const counts_2 = countByVec.countBy(x => x % 2 === 0);
console.log(counts_2);
// => [ [ false, 9 ], [ true, 8 ] ]

Vec.create(count, value) ⇒ Vec

Creates a vector whose elements are all initially the given value.

Returns: Vec - The created vector.

Param Type Description
count number The length of the vector to create.
value * The value for the elements.

Example

const createdVec = Vec.create(10, 2);
console.log(createdVec);
// => [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 ]

distinct() ⇒ Vec

Returns a vector that contains no duplicate entries. If an element occurs multiple times in the vector then the later occurrences are discarded.

Returns: Vec - The result vector.
Throws:

  • TypeError if struturalEquality parameter is null or undefined.

Example

const mixedVec = Vec.of(1, 1, 1, 2, 2, 2, 3, 3, 3, { n: 1 }, { n: 1 });
const distinctVec_1 = mixedVec.distinct(false);
console.log(distinctVec_1);
// => [ 1, 2, 3, { n: 1 }, { n: 1 } ]
const distinctVec_2 = mixedVec.distinct(true);
console.log(distinctVec_2);
// => [ 1, 2, 3, { n: 1 } ]

distinctBy(projection) ⇒ Vec

Returns a vector that contains no duplicate entries according to the equality comparisons on the keys returned by the given key-generating function. If an element occurs multiple times in the array then the later occurrences are discarded.

Returns: Vec - The result vector.
Throws:

  • TypeError if struturalEquality parameter is null or undefined; or projection parameter is a generator function
Param Type Description
projection function A function transforming the vector items into comparable keys.

Example

const mixedVec = Vec.of(
   { name: "Fsharp", family: { name: "ML" } },
   { name: "OCaml", family: { name: "ML" } },
   { name: "C++", family: { name: "Smalltalk" } }
);
const distinctedByVec_1 = mixedVec.distinctBy(x => x.family, false);
console.log(distinctedByVec_1);
// =>
 [ { name: 'Fsharp', family: { name: 'ML' } },
   { name: 'OCaml', family: { name: 'ML' } },
   { name: 'C++', family: { name: 'Smalltalk' } } ]

const distinctedByVec_2 = mixedVec.distinctBy(x => x.family, true);
console.log(distinctedByVec_2);
// =>
 [ { name: 'Fsharp', family: { name: 'ML' } },
   { name: 'C++', family: { name: 'Smalltalk' } } ]

empty() ⇒ Vec

Returns an empty vector.

Returns: Vec - The empty vector.

Vec.every2(predicate, source1, source2) ⇒ boolean

Tests if all corresponding elements of the vector satisfy the given predicate pairwise. The predicate is applied to matching elements in the two collections up to the lesser of the two lengths of the collections. If any application returns false then the overall result is false and no further elements are tested. Otherwise; if one collection is longer than the other then { TypeError }will be thrown. Otherwise; true is returned.

Returns: boolean - True if all of the array elements satisfy the predicate.
Throws:

  • TypeError when predicate is not a function or predicate is a generator function or source1 is not an array or a vector or source2 is not an array or a vector or the lengths of source1 and source2 are not the same.
Param Type Description
predicate function The function to test the input elements.
source1 Array | Vec The first input array or vector.
source2 Array | Vec The second input array or vector.

Example

const vec1 = Vec.of(2, 4, 6);
const vec2 = Vec.of(8, 10, 12);
const isEven = x => x % 2 === 0;
const allEven = Vec.every2(isEven, vec1, vec2);
console.log(allEven);
// => true

except(...itemsToExclude) ⇒ Vec

Returns a new list with the distinct elements of the input array which do not appear in the itemsToExclude sequence.

Returns: Vec - A vector that contains the distinct elements of source vector that do not appear in itemsToExclude.
Throws:

  • TypeError if structuralEquality parameter is null or undefined.
Param Type Description
...itemsToExclude * A sequence whose elements that also occur in the source vector will cause those elements to be removed from the result.

Example

const nObjVec = Vec.of({ n: 1 }, { n: 1 }, { n: 2 }, { n: 2 }, { n: 2 }, { n: 4 });
const except_1 = nObjVec.except(false, { n: 1 }, { n: 4 });
console.log(except_1);
// no items excluded under same-value-zero equality, no objects are equal to one another unless they are referencing to the same instance
// => [ { n: 1 }, { n: 1 }, { n: 2 }, { n: 2 }, { n: 2 }, { n: 4 } ]
const except_2 = nObjVec.except(true, { n: 1 }, { n: 2 });
console.log(except_2);
// => [ { n: 4 } ]

findIndexRight(predicate) ⇒ number

Returns the index of the last element in the vector that satisfies the given predicate. Returns -1 if none of the elements satisfy the predicate.

Returns: number - The index of the first element in the array that satisfies the given predicate.
Throws:

  • TypeError if predicate is a generator function or not a function.
Param Type Description
predicate function The function to test the input elements.

Example

const nums = Vec.of(1, 2, 3, 4, 5, 6, 7, 8);
const indexRight = nums.findIndexRight(x => x % 2 === 1);
console.log(indexRight);
// => 6

findRight(predicate) ⇒ element of the vector or undefined

Returns the last element for which the given function returns 'true'. Returns undefined if none of the elements satisfy the predicate.

Returns: * - The last element for which predicate returns true.
Throws:

  • TypeError if predicate is a generator function or not a function.
Param Type Description
predicate function The function to test the input elements.

Example

const p1 = { x : 10, y : 50};
const p2 = { x : 10, y : 60};
const p3 = { x : 10, y : 70};
const nums = new Vec(p1, p2, p3);
const result = nums.findRight(({x}) => x === 10);
console.log(result);
// => { x: 10, y: 70 }

Vec.fold2(folder, state, source1, source2) ⇒ value

Applies a function to pairs of elements drawn from the two collections, left-to-right, threading an accumulator argument through the computation. The two input arrays must have the same lengths.

Returns: * - The final state.
Throws:

  • TypeError when state is null or undefined or folder is not a function or folder is a generator function or source1 is neither an array nor a vector or source2 is neither an array nor a vector or
Param Type Description
folder function The function to update the state given the input elements.
state * The initial state.
source1 Array | Vec The first input array or vector.
source2 Array | Vec The second input array or vector.

Example

const oneToTen_1 = Vec.init(10, x => x + 1);
const oneToTen_2 = Vec.init(10, x => x + 1);
const folder = (s, x, y) => x + y + s;
const state = Vec.fold2(folder, 0, oneToTen_1, oneToTen_2);
console.log(state);
// => 110

Vec.foldRight2(folder, source1, source2, state) ⇒ value

Apply a function to pairs of elements drawn from the two collections, right-to-left, threading an accumulator argument through the computation. The two input arrays must have the same lengths.

Returns: * - The final state.
Throws:

  • TypeError when state is null or undefined or folder is not a function or folder is a generator function or source1 is neither an array nor a vector or source2 is neither an array nor a vector.
Param Type Description
folder function The function to update the state given the input elements.
source1 Array | Vec The first input array or vector.
source2 Array | Vec The second input array or vector.
state * The initial state.

Example

const oneToHundred_1 = Vec.init(100, x => x + 1);
const oneToHundred_2 = Vec.init(100, x => x + 1);
const folderRight = (x, y, s) => x + y + s;
const foldRightState = Vec.foldRight2(folderRight, oneToHundred_1, oneToHundred_2, 0);
console.log(foldRightState);
// => 10100

Vec.forEach2(action, source1, source2)

Applies the given function to pair of elements drawn from matching indices in two arrays or vectors. The two input arrays or vectors must have the same lengths.

Throws:

  • TypeError when action is a generator function or action is not a function or source1 is neither an array nor a vector or source2 is neither an array nor a vector.
Param Type Description
action function The function to apply.
source1 Array | Vec The first input array or vector.
source2 Array | Vec The second input array or vector.

Example

const charVec_1 = Vec.of('a', 'b', 'c', 'd');
const charVec_2 = Vec.of('d', 'e', 'f', 'g');
const charVecResult = new Vec();
Vec.forEach2((a, b, index) => charVecResult.push(a + b + index), charVec_1, charVec_2);
console.log(charVecResult);
// => [ 'ad0', 'be1', 'cf2', 'dg3' ]

get(index) ⇒ element

Gets an element from an array.

Returns: * - The value of the array at the given index.

Param Type Description
index number The input index.

Example

const oddNums = Vec.of(1, 3, 5, 7);
const seven = oddNums.get(3);
console.log(seven);
// => 7

groupBy(projection) ⇒ Vec

Applies a key-generating function to each element of a vector and yields a vector of unique keys. Each unique key contains a vector of all elements that match to this key.

Returns: Vec - The result vector.
Throws:

  • TypeError when structuralEquality parameter is null or undefined or projection is a generator function or projection is not a function.
Param Type Description
projection function A function that transforms an element of the vector into a key.

Example

const langs = Vec.of(
   { name: "Fsharp", family: { name: "ML" } },
   { name: "OCaml", family: { name: "ML" } },
   { name: "C++", family: { name: "Smalltalk" }},
   { name: "C#", family: { name: "Smalltalk" }},
   { name: "FcukTheCoup", family: { name: "Generation Z" }},
);
const groupsByFamily = langs.groupBy(({family}) => family, true);
groupsByFamily.forEach(([key, values]) => {
   console.log(`key: ${key.name}`);
   console.log(`\tvalues: `);
   console.log(values);
});
// =>
key: ML
values:
 [ { name: 'Fsharp', family: { name: 'ML' } },
   { name: 'OCaml', family: { name: 'ML' } } ]
key: Smalltalk
values:
 [ { name: 'C++', family: { name: 'Smalltalk' } },
   { name: 'C#', family: { name: 'Smalltalk' } } ]
key: Generation Z
values:
 [ { name: 'FcukTheCoup', family: { name: 'Generation Z' } } ]

head() ⇒ element

Returns the first element of the vector.

Returns: * - The first element of the vector or undefined if the vector is empty.
Example

const oneToFour = Vec.init(5, x => x + 1);
const head = oneToFour.head();
console.log(head);
// => 1

Vec.init(count, initializer) ⇒ Vec

Generate a new Vec by invoking initializer function passed as the argument up to the given count.

Returns: Vec - The result vector.
Throws:

  • TypeError if count is a negative number; or initializer is a generator function or not a function.
Param Type Description
count number The maximum number of items to generate for the Vec.
initializer function A function that generates an item in the Vec from a given index.

Example

const fiveNums = Vec.init(5, x => x * 2);
console.log(fiveNums);
// => [0, 2, 4, 6, 8]

isEmpty() ⇒ boolean

Returns true if the vector is empty, otherwise; false.

Returns: boolean - True if the vector is empty.

Vec.isVec(source) ⇒ boolean

Checks if the given source is a vector or not.

Returns: boolean - True if the source is vector, otherwise; false.

Param Type Description
source * The source to check.

Example

console.log(Vec.isVec([]));
// => false
console.log(Vec.isVec({ n: 10 }));
// => false
console.log(Vec.isVec(Vec.of(1, 2, 3)));
// => true

last() ⇒ element

Returns the last element of the vector.

Returns: * - The last element of the vector.
Example

console.log(Vec.init(1000, x => x).last())
// => 999

Vec.map2(mapping, source1, source2) ⇒ Vec

Builds a new collection whose elements are the results of applying the given function to the corresponding elements of the two vectors/arrays pairwise. The two input arrays must have the same lengths.

Returns: Vec - The vector of transformed elements.
Throws:

  • TypeError when mapping is not a function or mapping is a generator function or source1 is neither an array nor a vector or source2 is neither an array nor a vector or the lengths of source1 and source2 are not the same.
Param Type Description
mapping function The function to transform the pairs of the input elements.
source1 Array | Vec The first input array or vector.
source2 Array | Vec The second input array or vector.

Example

const v1 = Vec.of(1, 2, 3, 4, 5);
const v2 = Vec.of(1, 2, 3, 4, 5);
const mapping = (x, y, index) => x + y + index;
const mapped2 = Vec.map2(mapping, v1, v2);
console.log(mapped2);
// => [ 2, 5, 8, 11, 14 ]

Vec.map3(mapping, source1, source2, source3) ⇒ Vec

Builds a new collection whose elements are the results of applying the given function to the corresponding elements of the three vectors/arrays pairwise. The two input arrays must have the same lengths.

Returns: Vec - The vector of transformed elements.
Throws:

  • TypeError when mapping is not a function or mapping is a generator function or source1 is neither an array nor a vector or source2 is neither an array nor a vector or source3 is neither an array nor a vector or the lengths of source1, source2, and source3 are not the same.
Param Type Description
mapping function The function to transform the pairs of the input elements.
source1 Array | Vec The first input array or vector.
source2 Array | Vec The second input array or vector.
source3 Array | Vec The third input array or vector.

Example

const vec_1 = Vec.of(1, 2, 3, 4, 5);
const vec_2 = Vec.of(1, 2, 3, 4, 5);
const vec_3 = Vec.of(1, 2, 3, 4, 5);
const mapping3 = (x, y, z, index) => x + y + z + index;
const mapped3 = Vec.map3(mapping3, vec_1, vec_2, vec_3);
console.log(mapped3);
// => [ 3, 7, 11, 15, 19 ]

mapFold(mapping, state) ⇒ Vec

Builds a new vector whose elements are the results of applying the given function to each of the elements of the source vector. The function is also used to accumulate a final value.

Returns: Vec - The vector of transformed elements, and the final accumulated value.
Throws:

  • TypeError when state is null or undefined or mapping is a generator function or mapping is not a function.
Param Type Description
mapping function The function to transform elements from the vector and accumulate the final value.
state * The initial state.

Example

const oneToTenVec = Vec.init(10, x => x + 1);
const mapFolder = (state, elem) => [ state + elem, state + elem];
const mapFoldResult = oneToTenVec.mapFold(mapFolder, 0);
console.log(mapFoldResult);
// => [ [ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 ], 55 ]

const funcsVec_1 = Vec.of(x => x + 1, x => x + 1);
const mapFolder_1 = (state, x) => [x(state), x(state)];
const mapFoldResult_1 = funcsVec_1.mapFold(mapFolder_1, 1);
console.log(mapFoldResult_1);
// => [ [ 2, 3 ], 3 ]

mapFoldRight(mapping, state) ⇒ Vec

Builds a new vector whose elements are the results of applying the given function to each of the elements of the source vector. The function is also used to accumulate a final value.

Returns: Vec - The vector of transformed elements, and the final accumulated value.
Throws:

  • TypeError when state is null or undefined or mapping is a generator function or mapping is not a function.
Param Type Description
mapping function The function to transform elements from the vector and accumulate the final value.
state * The initial state.

Example

const funcsVec_2 = Vec.of(x => x + 1, x => x + 1);
const mapFolder_2 = (x, state) => [x(state), x(state)];
const mapFoldResult_2 = funcsVec_2.mapFoldRight(mapFolder_2, 1);
console.log(mapFoldResult_2);
// => [ [ 3, 2 ], 3 ]

max() ⇒ number|undefined

Returns the greatest of all elements of the vector.

Returns: number | undefined - The maximum number if the vector contains number; otherwise, undefined.
Example

const oneKItems = Vec.init(1000, x => x * x);
const max = oneKItems.max();
console.log(max);
// => 998001

maxBy(projection) ⇒ number|undefined

Returns the greatest of all elements of the vector.

Returns: number | undefined - The maximum element.
Throws:

  • TypeError when projection is not a function or projection is a generator function.
Param Type Description
projection function The function to transform the elements into a certain type.

Example

const thousandNums = Vec.init(1000, x => x + 1);
const biggestPerfectNumberUnder1000 = thousandNums.maxBy(x => {
   const v = new Vec();
   for(let i = 1; i < x; i += 1) {
       if (x % i === 0) {
           v.push(i);
       }
   }
   if (!v.isEmpty() &&  v.reduce((x,y) => x + y) === x) return x;
});
console.log(biggestPerfectNumberUnder1000);
// => 496

min() ⇒ number|undefined

Returns the smallest of all elements of the vector.

Returns: number | undefined - The minimum number if the vector contains number; otherwise, undefined.
Example

const vec = Vec.of(1, 2, 3, 4, 5, 0);
const min = vec.min();
console.log(min);
// => 0

minBy(projection) ⇒ number|undefined

Returns the smallest of all elements of the vector.

Returns: number | undefined - The minimum element.
Throws:

  • TypeError when projection is not a function or projection is a generator function.
Param Type Description
projection function The function to transform the elements into a certain type.

Example

const thousandNums = Vec.init(1000, x => x + 1);
const smallestPerfectNumberUnder1000 = thousandNums.minBy(x => {
   const v = new Vec();
   for(let i = 1; i < x; i += 1) {
       if (x % i === 0) {
           v.push(i);
       }
   }
   if (!v.isEmpty() &&  v.reduce((x,y) => x + y) === x) return x;
});
console.log(smallestPerfectNumberUnder1000);
// => 6

pairwise() ⇒ Vec

Returns a vector of each element in the vector and its predecessor, with the exception of the first element which is only returned as the predecessor of the second element.

Returns: Vec - The result vector.
Example

const vowels = Vec.of('a', 'e', 'i', 'o', 'u');
const p = vowels.pairwise();
console.log(p);
// => [ [ 'a', 'e' ], [ 'e', 'i' ], [ 'i', 'o' ], [ 'o', 'u' ] ]

partition(predicate) ⇒ Vec

Splits the vector into two vectors, containing the elements for which the given predicate returns "true" and "false" respectively.

Returns: Vec - A pair of vectors. The first containing the elements the predicate evaluated to true, and the second containing those evaluated to false.
Throws:

  • TypeError when predicate is not a function or predicate is a generator function.
Param Type Description
predicate function The function to test the input elements.

Example

const twelveNums = Vec.init(12, x => x + 1);
const [evens, odds] = twelveNums.partition(x => x % 2 === 0);
console.log(evens);
// => [ 2, 4, 6, 8, 10, 12 ]
console.log(odds);
// => [ 1, 3, 5, 7, 9, 11 ]

permute() ⇒ Vec

Returns a vector with all elements permuted. The quickperm algorithm is used. https://www.quickperm.org/quickperm.php

Returns: Vec - The result vector.
Example

const threeNums = Vec.of(1, 2, 3);
const permuted = threeNums.permute();
console.log(permuted);
// =>
//  [ [ 1, 2, 3 ],
//    [ 2, 1, 3 ],
//    [ 3, 1, 2 ],
//    [ 1, 3, 2 ],
//    [ 2, 3, 1 ],
//    [ 3, 2, 1 ] ]

scan(folder, initialState) ⇒ Vec

Like reduce method, but return the intermediary and final results.

Returns: Vec - The result vector.
Throws:

  • TypeError when initialState is null or undefined. Or folder is not a function or folder is a generator function.
Param Type Description
folder function The function to update the state given the input elements.
initialState * The initial state.

Example

const tenNumbers = Vec.init(10, x => x + 1);
const scanned = tenNumbers.scan((state, elem) => state + elem, 0);
console.log(scanned);
// => [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 ]
const threeFuncs = Vec.of(x => x - 1, x => x - 2, x => x - 3);
const scannedValues = threeFuncs.scan((state, f) => f(state), 1);
console.log(scannedValues)
// => [ 1, 0, -2, -5 ]

scanRight(folder, initialState) ⇒ Vec

Like reduceRight method, but return the intermediary and final results.

Returns: Vec - The result vector.
Throws:

  • TypeError when initialState is null or undefined. Or folder is not a function or folder is a generator function.
Param Type Description
folder function The function to update the state given the input elements.
initialState * The initial state.

Example

const threeFuncs_1 = Vec.of(x => x - 1, x => x - 2, x => x - 3);
const scannedValues_1 = threeFuncs_1.scanRight((f, state) => f(state), 1);
console.log(scannedValues_1)
// => [ -5, -4, -2, 1 ]

set(index, value) ⇒ Vec

Sets an element of a vector.

Returns: * - The value set.

Param Type Description
index number The index to add an element.
value * The value to add into the vector at the given index.

Example

const newVec = new Vec();
const setVal = newVec.set(5, 256);
console.log(setVal);
// => 256
console.log(newVec);
// => [ , , , , , 256 ]

skipWhile(predicate) ⇒ Vec

Bypasses elements in the vector while the given predicate returns True, and then returns the remaining elements in a new vector.

Returns: Vec - The result vector.
Throws:

  • TypeError when predicate is not a function or predicate is a generator function.
Param Type Description
predicate function A function that evaluates an element of the vector to a boolean value.

Example

const randomVec = Vec.of(11, 3, 2, 4, 100, 65, 100, 2,);
const skipWhileResult = randomVec.skipWhile(x => x < 100);
console.log(skipWhileResult);
// => [ 100, 65, 100, 2 ]

some2(predicate, source1, source2) ⇒ boolean

Tests if any pair of corresponding elements of the vectors satisfies the given predicate. The predicate is applied to matching elements in the two collections up to the lesser of the two lengths of the collections. If any application returns true then the overall result is true and no further elements are tested.

Returns: boolean - True if any result from predicate is true. Otherwise, false.
Throws:

  • TypeError when predicate is not a function or predicate is a generator function or source1 is not an array or a vector or source2 is not an array or a vector or the lengths of source1 and source2 are not the same.
Param Type Description
predicate function The function to test the input elements.
source1 Array | Vec The first input vector.
source2 Array | Vec The second input vector.

Example

const fourNumbers_1 = Vec.of(25, 4, 55, 61);
const fourNumbers_2 = Vec.of(2, 4, 5, 56);
const hasEvenPair = Vec.some2((x, y) => x % 2 === 0 && y % 2 === 0, fourNumbers_1, fourNumbers_2);
console.log(hasEvenPair);
// => true

splitAt(index) ⇒ Vec

Splits the vector into two vectors, at the given index.

Returns: Vec - The result vector that contains the two split vectors.
Throws:

  • TypeError When index is negative.
Param Type Description
index number The index at which the vector is split.

Example

const twentyNumbers = Vec.init(20, x => x + 1);
const splitVec = twentyNumbers.splitAt(10);
console.log(splitVec);
// => [ [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ], [ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ] ]

sum() ⇒ number|undefined

Returns the sum of the elements in the vector.

Returns: number | undefined - The sum of the elements in the vector if all the elements are number. Otherwise, undefined.
Example

const fiveNumbers = Vec.of(10,20,30,40,50);
const sum = fiveNumbers.sum();
console.log(sum);
// => 150

sumBy(projection) ⇒ number|undefined

Returns the sum of the results generated by applying the function to each element of the vector.

Returns: number | undefined - The resulting sum.

Param Type Description
projection function The function to transform the vector elements into the type to be summed.

Example

const hundredNumbers = Vec.init(100, x => x + 1);
const sumOfEvens = hundredNumbers.sumBy(x => x % 2 === 0 ? x : 0);
console.log(sumOfEvens);
// => 2550
const sumOfOdds = hundredNumbers.sumBy(x => x % 2 === 1 ? x : 0);
console.log(sumOfOdds);
// => 2500

tail() ⇒ Vec

Returns a new array containing the elements of the original except the first element.

Returns: Vec - A new vector containing the elements of the original except the first element. If the vector is empty, empty vector will be returned.
Example

const sixNumbers = Vec.of(6, 5, 4, 3, 2, 1);
const tail = sixNumbers.tail();
console.log(tail);
// => [ 5, 4, 3, 2, 1 ]

take(count) ⇒ Vec

Returns the first N elements of the vector.

Returns: Vec - The result vector.

Param Type Description
count number The number of items to take.

Example

const zeroToTen = Vec.init(11, x => x);
const firstFive = zeroToTen.take(5);
console.log(firstFive);
// => [ 0, 1, 2, 3, 4 ]

takeWhile(predicate) ⇒ Vec

Returns a vector that contains all elements of the original vector while the given predicate returns True, and then returns no further elements.

Returns: Vec - The result vector.
Throws:

  • TypeError When predicate is not a function, or predicate is a generator function.
Param Type Description
predicate function A function that evaluates to false when no more items should be returned.

Example

const oddsVec = Vec.of(99, 89, 11, 23, 3,9 , 11);
const takeWhileVec = oddsVec.takeWhile(x => x > 11);
console.log(takeWhileVec);
// => [ 99, 98 ]

transpose() ⇒ Vec

Returns the transpose of the vector.

Returns: Vec - The transposed vector.
Example

const matrix = Vec.of([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]);
const tranposed = matrix.transpose();
console.log(tranposed);
// => [ [ 1, 6 ], [ 2, 7 ], [ 3, 8 ], [ 4, 9 ], [ 5, 10 ] ]

unfold(generator, state) ⇒ Vec

Returns a vector that contains the elements generated by the given computation. The given initial state argument is passed to the element generator.

Returns: Vec - The result vector.
Throws:

  • TypeError When generator is not a function or generator is a generator function.
Param Type Description
generator function A function that takes in the current state and returns an array containing next element of the vector and the next state value.
state * The initial state value.

Example

const oneToTwenty = Vec.unfold(x => x <= 20 ? [x, x + 1] : undefined, 1);
console.log(oneToTwenty);
// => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
const fib = (n) => Vec.unfold(([x, [a, b]]) => (x < n ? [a + b, [x + 1, [b, a + b]]] : null), [0, [0, 1]]);
const fibSeries = fib(10);
console.log(fibSeries);
// => [ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]

unzip() ⇒ Vec

Splits a vector of pairs into two vectors.

Returns: Vec - The vector containing two vectors.
Example

const pairsOfVec = new Vec(
   new Vec(1, 2),
   new Vec(3, 4),
   new Vec(5, 6)
);
const unzipped = pairsOfVec.unzip();
console.log(unzipped);
// => [ [ 1, 3, 5 ], [ 2, 4, 6 ] ]

windowed(windowSize) ⇒ Vec

Returns a vector of sliding windows containing elements drawn from the source vector. Each window is returned as a fresh vector.

Returns: Vec - The result array.
Throws:

  • TypeError When windowSize is negative.
Param Type Description
windowSize number The number of elements in each window.

Example

const zeroToFive = Vec.init(6, x => x);
const windows = zeroToFive.windowed(2);
console.log(windows);
// => [ [ 0, 1 ], [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ]

zip(other) ⇒ Vec

Combines the two vectors into a vector of pairs. The two vectors must have equal lengths

Returns: Vec - The vector of pairs.
Throws:

  • TypeError when other is null or undefined or the lengths of the source and other vectors are not the same.
Param Type Description
other Vec The other input vector.

Example

const oneToFourVec = Vec.of(1, 2, 3, 4);
const fiveToEightVec = Vec.of(5, 6, 7, 8);
const zipped = oneToFourVec.zip(fiveToEightVec);
console.log(zipped);
// => [ [ 1, 5 ], [ 2, 6 ], [ 3, 7 ], [ 4, 8 ] ]

Vec.zip3(source1, source2, source3) ⇒ Vec

Combines three vectors into a vector of pairs. The three vectors must have equal lengths.

Returns: Vec - The result vector.
Throws:

  • TypeError when source1 is neither an array nor a vector or source2 is neither an array nor a vector or source3 is neither an array nor a vector or the lengths of source1, source2, and source3 are not the same.
Param Type Description
source1 Array | Vec The first input array or vector.
source2 Array | Vec The second input array or vector.
source3 Array | Vec The third input array or vector.

Example

const sevenNumbers_1 = Vec.init(7, x => x);
const sevenNumbers_2 = Vec.init(7, x => x + x);
const sevenNumbers_3 = Vec.init(7, x => x * x);
const zipped3 = Vec.zip3(sevenNumbers_1, sevenNumbers_2, sevenNumbers_3);
console.log(zipped3);
// =>
 [ [ 0, 0, 0 ],
   [ 1, 2, 1 ],
   [ 2, 4, 4 ],
   [ 3, 6, 9 ],
   [ 4, 8, 16 ],
   [ 5, 10, 25 ],
   [ 6, 12, 36 ] ]