array-to-object-keys
Version:
Converts an array to an object where the keys are the array entries and the values are customizable in a function.
71 lines • 3.11 kB
TypeScript
/** @module array-to-object-keys
*/
declare module "array-to-object-keys" {
/**
* @typedef valueGenerator
* @type {function}
* @param {string} value Original array entry
* @param {number} index Index of the array entry (starts at 0)
* @returns {*} Anything that will be the object entry value
*/
export type valueGenerator = (value: string, index: number) => any;
/**
* @typedef asyncValueGenerator
* @type {function}
* @async
* @param {string} value Original array entry
* @param {number} index Index of the array entry (starts at 0)
* @returns {*} Anything that will be the object entry value
*/
export type asyncValueGenerator = (value: string, index: number) => any;
/**
* Converts an array to an object with static keys and customizable values
* @example
* import arrayToObjectKeys from "array-to-object-keys"
* let result = arrayToObjectKeys(["a", "b"])
* result = {a: null, b: null}
* @example
* import arrayToObjectKeys from "array-to-object-keys"
* let result = arrayToObjectKeys(["a", "b"], "value")
* result = {a: "value", b: "value"}
* @example
* import arrayToObjectKeys from "array-to-object-keys"
* let result = arrayToObjectKeys(["a", "b"], (key, index) => `value for ${key} #${index + 1}`)
* result = {a: "value for a #1", b: "value for b #2"}
* @function
* @param {string[]} array Keys for the generated object
* @param {valueGenerator|*} [valueGenerator=null] Optional function that sets the object values based on key and index
* @returns {object<string, *>} A generated object based on the array input
*/
export default function(array: string[], valueGenerator?: valueGenerator | any): {
[key: string]: any;
};
/**
* Converts an array to an object with static keys and customizable values
* @example
* import fs from "fs"
* import path from "path"
* import {parallel} from "array-to-object-keys"
* const keys = ["license", "readme", "package", ".travis", "not-here"]
* const valueGenerator = async name => {
* const files = await fs.promises.readdir(path.resolve(__dirname, ".."))
* for (const file of files) {
* if (file.startsWith(`${name}.`)) {
* const stat = await fs.promises.stat(path.resolve(__dirname, "..", file), "utf8")
* return stat.size
* }
* }
* return null
* }
* let result = await parallel(keys, valueGenerator)
* result = { ".travis": 1672, license: 1099, package: 1948, readme: 132, "not-here": null }
* @async
* @function
* @param {string[]} array Keys for the generated object
* @param {asyncValueGenerator|*} [valueGenerator=null] Async function that sets the object values based on key and index
* @returns {Promise<object<string, *>>} A generated object based on the array input
*/
export function parallel(array: string[], valueGenerator?: asyncValueGenerator | any): Promise<{
[key: string]: any;
}>;
}