Логика функции уменьшения и распространения с использованием одной строки оператора if - PullRequest
1 голос
/ 18 апреля 2019

У меня проблемы с пониманием оператора if для этого примера сокращения:

const colors = ['red', 'red', 'green', 'blue', 'green', 'yellow'];
console.log(colors);

const distinctColors = colors.reduce(
    (distinct, color) =>
        (distinct.indexOf(color) !== -1) ? 
            distinct : 
            [...distinct, color], []
)

console.log(distinctColors)

Я пытаюсь понять оператор if в псевдокоде, и, читая этот пример, я вижу следующее:


If the color found in the distinct array (which is empty)
  return empty array
else
  return contents of array and color added to an empty array

Я - яблизко или далеко?

тестирование repl.it здесь

Ответы [ 2 ]

1 голос
/ 18 апреля 2019

Пытался объяснить с комментариями, надеюсь, это поможет.

const colors = ['red', 'red', 'green', 'blue', 'green', 'yellow'];
console.log(colors);

const distinctColors = colors.reduce(
    (distinct, color) =>
        (distinct.indexOf(color) !== -1) ? 
        // ----------------^ Turnary to test for presence of current color in the accum []
            distinct : 
        // ----^ It DOES exist, so return the current Accum array    
            [...distinct, color], []
            // ---^ Is DOES NOT exist, return a new array of Accum + Color
            // --------------------^ This initialises a new empty array into the accumulator
)

console.log(distinctColors)

Только что добавил это для справки, использование набора для этого гораздо эффективнее.

const colors = ['red', 'red', 'green', 'blue', 'green', 'yellow'];
console.log(colors);

const distinctColors = [...new Set(colors)];

console.log(distinctColors)

Вот документация MDN по Set. Набор Javascript

0 голосов
/ 18 апреля 2019

Уменьшает массив до его уникальных значений.Вы можете прочитать это как:

Установить distinct в пустой массив (2-й параметр, чтобы уменьшить).Для каждого color в colors, если color в distinct (индекс! == -1), обновите distinct до distinct (без операции) (первая троичная ветвь), иначе, еслиcolor отсутствует в distinct, обновите distinct до distinct + color (2-я тройная ветвь).

См. Документацию mdn reduce.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...