Обновить
0

Пользователь

Отправить сообщение
Спасибо за статью, было интересно. Вот тесты:

императив
const result = []

for (let i = 0; i < scores.length && result.length < 2; i++) {
  const { gameID, my, others } = scores[i]

  if (my > others) {
    result.push(gameID)
  }
}


трансдьюсер
class Reduced {
  constructor(value) {
    this.value = value
  }
}

const isReduced = value => value instanceof Reduced

const reduced = value => isReduced(value) ? value : new Reduced(value)

const reduce = (reducer, state, array) => {
  if (isReduced(state)) {
    return state.value
  }
  if (array.length === 0) {
    return state
  }

  const [x, ...xs] = array
  return reduce(reducer, reducer(state, x), xs)
}

const filter = pred => next => (acc, x) =>
  pred(x) ? next(acc, x) : acc

const map = mapper => next => (acc, x) =>
  next(acc, mapper(x))

const take = n => next => (acc, x) => {
  if (n > 0) {
    acc = next(acc, x)
    n -= 1
  }
  if (n <= 0) {
    acc = reduced(acc)
  }

  return acc
}

const append = (xs, x) =>
  xs.concat([x])

const compose = (...fns) => x =>
  fns.reduceRight((x, fn) => fn(x), x)

const transduce = (transducer, reducer, init, array) =>
  reduce(transducer(reducer), init, array)

const firstTwoWins = compose(
  filter(({ my, others }) => my > others),
  map(({ gameID }) => gameID),
  take(2)
)

const result = transduce(firstTwoWins, append, [], scores)


объекты
function takeFrom(arr, {filter, take, max}) {
  let counter = 0,
      result = []

  for (let i = 0; i < arr.length; i++) {
    if (filter(arr[i])) {counter++; result.push(arr[i][take])}
    if (max && counter == max) return result
  }
  return result
}

const firstTwoWins = {
  filter: ({my, others}) => my > others,
  take  : 'gameID',
  max   : 2
}

takeFrom(scores, firstTwoWins)


на правах изврата
  const win = ({my, others}) => my > others
  const firstResult = scores.findIndex(win)
  const secondResult = firstResult + 1 + scores.slice(firstResult + 1).findIndex(win)


повседневный
const result =
  scores
    .filter(({ my, others }) => my > others)
    .map(({ gameID }) => gameID)
    .slice(0, 2)



Результаты:
количество операций за 1 секунду, время выполнения операции

элементов в массиве    10          100        100 000    1 000 000

  императив          1 360 836   1 347 020   1 454 109   1 426 568
                        0           0           0           0

  трансдюсер         361 359      63 541       47           5 (1 если элементы конечные)
                        0           0          28          247 (1 066 если элементы конечные)

  обьекты            1 194 086   1 151 443   1 128 703   1 160 694
                        0           0           0           0

  на правах изврата  904 147     809 852      1 436        139
                        0           0           1           5

  повседневный       281 325      47 045       49           5
                        0           1          26          224


Информация

В рейтинге
Не участвует
Зарегистрирован
Активность