JSFiddle - React, Tailwind, and code Playground
by gianlucaguarini
JavaScript
function toArray(collection, to) {
// Special case: handle numbers
if (typeof to !== 'undefined') {
if (isNumber(collection) && isNumber(to)) {
return Array.from({ length: (to - collection + 1) }, (v, key) => [collection + key, collection + key]);
}
throw new TypeError('Both arguments need to be a number when creating a number range.');
}
// handle falsy values
if (!collection) {
return [];
}
// handle objects with an 'entries' function
// such as: Arrays, Maps, Sets, NodeLists...
if (typeof collection.entries === 'function') {
return [...collection.entries()].map(entry => entry.reverse());
}
// Default for all other object types, strings, booleans and symbols
return Object
.keys(collection)
.map((key) => {
return [collection[key], key];
});
}
toArray('123').map(([value, key], index) => console.log(typeof key))
toArray(['1', '2', '3']).map(([value, key], index) => console.log(typeof key))