跳到主要内容

map

TS JS Deno

Creates a new map with the results of calling a provided function on every value in the calling function.

Use Array.isArray() to detect array, else destructure array like data(string). Use Array.prototype.map() to map array of data.

typescript
const map = <T = any>(array: Iterable<T>, fn: MapFunc<T>) => {
const chars = Array.isArray(array) ? array : [...array];
return chars.map((c, i) => fn(c, i, chars));
};
typescript
// map array of chars
map("lorem ipsum", (c) => c.toUpperCase()).join("")) // "LOREM IPSUM"

// map array of numbers
map([1, 2, 3, 4], (c) => c * c)); // [1, 4, 9, 16]