aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/utils/arrays.js
blob: c0d6962648532e367789444dfecb3b81e5254c44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// ==========================================================================
// Array utils
// ==========================================================================

import is from './is';

// Remove duplicates in an array
export function dedupe(array) {
    if (!is.array(array)) {
        return array;
    }

    return array.filter((item, index) => array.indexOf(item) === index);
}

// Get the closest value in an array
export function closest(array, value) {
    if (!is.array(array) || !array.length) {
        return null;
    }

    return array.reduce((prev, curr) => (Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev));
}

export function fillRange(start, end, step = 1) {
    const len = Math.floor((end - start) / step) + 1;

    return Array(len)
        .fill()
        .map((_, idx) => start + idx * step);
}