UNPKG

locutus

Version:

Locutus other languages' standard libraries to JavaScript for fun and educational purposes

25 lines (24 loc) 1.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.associateBy = associateBy; function associateBy(values, keySelector) { // discuss at: https://locutus.io/kotlin/collections/associateBy/ // original by: Kevin van Zonneveld (https://kvz.io) // note 1: Builds a key->element map using keySelector, with the last duplicate key winning (Kotlin associateBy behavior). // example 1: associateBy(['ant', 'bear', 'cat'], (s) => s.charAt(0)) // returns 1: {a: 'ant', b: 'bear', c: 'cat'} // example 2: associateBy([1, 2, 3, 4], (n) => n % 2) // returns 2: {'0': 4, '1': 3} // example 3: associateBy([], () => 'x') // returns 3: {} if (!Array.isArray(values) || typeof keySelector !== 'function') { return {}; } const out = {}; for (let i = 0; i < values.length; i++) { const value = values[i]; const key = String(keySelector(value, i, values)); out[key] = value; } return out; }