array.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * Calls a defined callback function on each key:value of a object,
  3. * and returns a object contains the result.
  4. */
  5. export function mapObject(object, callbackfn) {
  6. return Object.entries(object).reduce((obj, [key, value]) => {
  7. obj[key] = callbackfn(value, key, object);
  8. return obj;
  9. }, {});
  10. }
  11. export function indexOf(array) {
  12. return array.map((_, i) => i);
  13. }
  14. /**
  15. * @example [[1, 2, 3], ['a', 'b', 'c']] => [[1, 'a'], [2, 'b'], [3, 'c']]
  16. */
  17. export function transpose(matrix) {
  18. const row = matrix.length;
  19. const col = matrix[0].length;
  20. // Note: new Array(col).fill(new Array(row)) is not ok!!!
  21. // Because in this case it will fill new Array(col) with the same array: new Array(row).
  22. const transposed = new Array(col).fill(0).map(() => new Array(row));
  23. for (let i = 0; i < col; i++) {
  24. for (let j = 0; j < row; j++) {
  25. transposed[i][j] = matrix[j][i];
  26. }
  27. }
  28. return transposed;
  29. }
  30. export function firstOf(array) {
  31. return array[0];
  32. }
  33. export function lastOf(array) {
  34. return array[array.length - 1];
  35. }
  36. export function isFlatArray(array) {
  37. return !array.some(Array.isArray);
  38. }
  39. export function unique(array) {
  40. return Array.from(new Set(array));
  41. }
  42. export function divide(array, callbackfn) {
  43. const result = [[], []];
  44. array.forEach((item) => {
  45. result[callbackfn(item) ? 0 : 1].push(item);
  46. });
  47. return result;
  48. }
  49. function comb(array, len = array.length) {
  50. if (len === 1)
  51. return array.map((item) => [item]);
  52. const result = [];
  53. for (let i = 0; i < array.length; i++) {
  54. const rest = array.slice(i + 1);
  55. const restComb = comb(rest, len - 1);
  56. restComb.forEach((comb) => {
  57. result.push([array[i], ...comb]);
  58. });
  59. }
  60. return result;
  61. }
  62. /**
  63. * get all combinations of two elements in an array
  64. * @example [1, 2, 3] => [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
  65. * @param array
  66. * @returns
  67. */
  68. export function combine(array) {
  69. if (array.length === 1)
  70. return [array];
  71. const result = [];
  72. for (let i = 1; i <= array.length; i++) {
  73. result.push(...comb(array, i));
  74. }
  75. return result;
  76. }
  77. //# sourceMappingURL=array.js.map