interpolate.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. *
  3. * @param {number|number[]|string|string[]} from
  4. * @param {number|number[]|string|string[]} to
  5. * @param {number} ratio
  6. * @param {Function} [parser]
  7. * @param {Function} [formatter]
  8. * @returns {any}
  9. */
  10. export type FromTo = string | number | (string | number)[];
  11. export type Parser = (value: FromTo) => any;
  12. export type Formatter = (value: any[]) => any;
  13. // eslint-disable-next-line max-len
  14. export default function interpolate(from: FromTo, to: FromTo, ratio = 0, parser: Parser = null, formatter: Formatter = null) {
  15. if (typeof parser === 'function') {
  16. from = parser(from);
  17. to = parser(to);
  18. }
  19. if (typeof from === 'string' || typeof from === 'number') {
  20. from = [parseFloat(from as string)];
  21. }
  22. if (typeof to === 'string' || typeof to === 'number') {
  23. to = [parseFloat(to as string)];
  24. }
  25. const result: any[] = [];
  26. if (Array.isArray(from) && Array.isArray(to)) {
  27. from.forEach((fromVal, idx) => {
  28. fromVal = parseFloat(fromVal as string);
  29. const toVal = parseFloat(to[idx]);
  30. result.push((toVal - fromVal) * ratio + fromVal);
  31. });
  32. }
  33. if (typeof formatter === 'function') {
  34. return formatter(result);
  35. } else {
  36. return result;
  37. }
  38. }