array.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * from https://github.com/dsehnal/CIFTools.js
  5. * @author David Sehnal <david.sehnal@gmail.com>
  6. */
  7. import { ArrayCtor } from '../../mol-util/type-helpers';
  8. export function arrayFind<T>(array: ArrayLike<T>, f: (v: T) => boolean): T | undefined {
  9. for (let i = 0, _i = array.length; i < _i; i++) {
  10. if (f(array[i])) return array[i];
  11. }
  12. return void 0;
  13. }
  14. export function iterableToArray<T>(it: IterableIterator<T>): T[] {
  15. if (Array.from) return Array.from(it);
  16. const ret = [];
  17. while (true) {
  18. const { done, value } = it.next();
  19. if (done) break;
  20. ret[ret.length] = value;
  21. }
  22. return ret;
  23. }
  24. /** Fills the array so that array[0] = start and array[array.length - 1] = end */
  25. export function createRangeArray(start: number, end: number, ctor?: ArrayCtor<number>) {
  26. const len = end - start + 1;
  27. const array = ctor ? new ctor(len) : new Int32Array(len);
  28. for (let i = 0; i < len; i++) {
  29. array[i] = i + start;
  30. }
  31. return array;
  32. }
  33. export function arrayPickIndices<T>(array: ArrayLike<T>, indices: ArrayLike<number>) {
  34. const ret = new (arrayGetCtor(array))(indices.length);
  35. for (let i = 0, _i = indices.length; i < _i; i++) {
  36. ret[i] = array[indices[i]];
  37. }
  38. return ret;
  39. }
  40. export function arrayGetCtor<T>(data: ArrayLike<T>): ArrayCtor<T> {
  41. const ret = (data as any).constructor;
  42. if (!ret) throw new Error('data does not define a constructor and it should');
  43. return ret;
  44. }