UNPKG

genetic-search

Version:

Multiprocessing genetic algorithm implementation library

95 lines 2.96 kB
/** * Sorts an iterable of values based on a custom comparator. * * @template T - The type of the iterable to be sorted. * @param data - The iterable to be sorted. * @param comparator - The comparator function to be used for sorting. * @returns An iterable of the sorted values. * * @example * const numbers = [1, 2, 3]; * const sorted = sort(numbers, (lhs, rhs) => lhs - rhs); * for (const number of sorted) { * console.log(number); * } * // Prints 1, 2, 3 * * @category IterTools */ export function* sort(data, comparator) { const result = [...data]; result.sort(comparator); for (const datum of result) { yield datum; } } /** * Repeats the given item the specified number of times. * * @template T - The type of the item to be repeated. * @param item - The item to be repeated. * @param repetitions - The number of times to repeat the item. * @returns An iterable of the repeated items. * * @category IterTools */ export function* repeat(item, repetitions) { for (let i = repetitions; i > 0; --i) { yield item; } } /** * Combines multiple iterables into a single iterable of tuples. Each tuple * contains the elements from the input iterables at the same position. * * @template T - An array of iterables to be zipped together. * @param iterables - The iterables to be zipped. * @returns An iterable of tuples, where each tuple contains elements from * each of the input iterables at the corresponding position. * * @example * const numbers = [1, 2, 3]; * const letters = ['a', 'b', 'c']; * for (const pair of zip(numbers, letters)) { * console.log(pair); // Logs: [1, 'a'], [2, 'b'], [3, 'c'] * } * * @category IterTools */ export function* zip(...iterables) { const iterators = iterables.map(iterable => iterable[Symbol.iterator]()); iterate: while (true) { const tuple = []; for (const iterator of iterators) { const next = iterator.next(); if (next.done) { break iterate; } tuple.push(next.value); } yield tuple; } } /** * Returns an iterable of unique elements from the input data, where uniqueness * is determined by the value returned from the provided `compareBy` function. * * @template T - The type of elements in the input data. * @param data - The input iterable containing elements to be filtered for uniqueness. * @param compareBy - A function that takes an element from the input data and * returns a comparable value to determine uniqueness. * @returns An iterable of unique elements from the input data. * * @category IterTools */ export function* distinctBy(data, compareBy) { const used = new Set(); for (const datum of data) { const comparable = compareBy(datum); if (!used.has(comparable)) { yield datum; used.add(comparable); } } } //# sourceMappingURL=itertools.js.map