10 ЈаваСцрипт услужних функција направљених са Редуце
Вишенаменски алат поново удара.
У свом последњем чланку понудио сам вам изазов за поновно стварање добро познатих функција помоћу reduce
. Овај чланак ће вам показати како се неки од њих могу применити, заједно са неким додацима!
Укупно ћемо размотрити десет корисних функција. Невероватно су вам при руци у вашим пројектима, а што је најбоље, имплементирани су помоћу reduce
! За ову сам извукао пуно инспирације из РамдаЈС библиотеке, па погледајте то!
1. неки
Параметри
predicate
- Функција која се враћаtrue
илиfalse
.array
- Списак предмета за тестирање.
Опис
Ако се predicate
врати true
за било који предмет, some
враћа се true
. У супротном се враћа false
.
Имплементација
const some = (predicate, array) => array.reduce((acc, value) => acc || predicate(value), false);
Употреба
const equals3 = (x) => x === 3; some(equals3, [3]); // true some(equals3, [3, 3, 3]); // true some(equals3, [1, 2, 3]); // true some(equals3, [2]); // false
2. сви
Параметри
predicate
- Функција која се враћаtrue
илиfalse
.array
- Списак предмета за тестирање.
Опис
Ако се predicate
враћа true
за сваку ставку, all
враћа се true
. У супротном се враћа false
.
Имплементација
const all = (predicate, array) => array.reduce((acc, value) => acc && predicate(value), true);
Употреба
const equals3 = (x) => x === 3; all(equals3, [3]); // true all(equals3, [3, 3, 3]); // true all(equals3, [1, 2, 3]); // false all(equals3, [3, 2, 3]; // false
3. ниједан
Параметри
predicate
- Функција која се враћаtrue
илиfalse
.array
- Списак предмета за тестирање.
Опис
Ако се predicate
враћа false
за сваку ставку, none
враћа се true
. У супротном се враћа false
.
Имплементација
const none = (predicate, array) => array.reduce((acc, value) => !acc && !predicate(value), false);
Употреба
const isEven = (x) => x % 2 === 0; none(isEven, [1, 3, 5]); // true none(isEven, [1, 3, 4]); // false none(equals3, [1, 2, 4]); // true none(equals3, [1, 2, 3]); // false
4. карта
Параметри
transformFunction
- Функција за покретање сваког елемента.array
- Списак предмета за трансформисање.
Опис
Враћа нови низ предмета, сваки трансформисан према датом transformFunction
.
Имплементација
const map = (transformFunction, array) => array.reduce((newArray, item) => { newArray.push(transformFunction(item)); return newArray; }, []);
Употреба
const double = (x) => x * 2; const reverseString = (string) => string .split('') .reverse() .join(''); map(double, [100, 200, 300]); // [200, 400, 600] map(reverseString, ['Hello World', 'I love map']); // ['dlroW olleH', 'pam evol I']
5. филтер
Параметри
predicate
- Функција која се враћаtrue
илиfalse
.array
- Списак предмета за филтрирање.
Опис
Враћа нови низ. Ако се predicate
врати true
, та ставка се додаје у нови низ. Иначе је та ставка изузета из новог низа.
Имплементација
const filter = (predicate, array) => array.reduce((newArray, item) => { if (predicate(item) === true) { newArray.push(item); } return newArray; }, []);
Употреба
const isEven = (x) => x % 2 === 0; filter(isEven, [1, 2, 3]); // [2] filter(equals3, [1, 2, 3, 4, 3]); // [3, 3]
6. одбити
Параметри
predicate
- Функција која се враћаtrue
илиfalse
.array
- Списак предмета за филтрирање.
Опис
Баш као filter
, али са супротним понашањем.
Ако се predicate
врати false
, та ставка се додаје у нови низ. Иначе је та ставка изузета из новог низа.
Имплементација
const reject = (predicate, array) => array.reduce((newArray, item) => { if (predicate(item) === false) { newArray.push(item); } return newArray; }, []);
Употреба
const isEven = (x) => x % 2 === 0; reject(isEven, [1, 2, 3]); // [1, 3] reject(equals3, [1, 2, 3, 4, 3]); // [1, 2, 4]
7. find
Parameters
predicate
- Function that returnstrue
orfalse
.array
- List of items to search.
Description
Returns the first element that matches the given predicate
. If no element matches then undefined
is returned.
Implementation
const find = (predicate, array) => array.reduce((result, item) => { if (result !== undefined) { return result; } if (predicate(item) === true) { return item; } return undefined; }, undefined);
Usage
const isEven = (x) => x % 2 === 0; find(isEven, []); // undefined find(isEven, [1, 2, 3]); // 2 find(isEven, [1, 3, 5]); // undefined find(equals3, [1, 2, 3, 4, 3]); // 3 find(equals3, [1, 2, 4]); // undefined
8. partition
Parameters
predicate
- Function that returnstrue
orfalse
.array
- List of items.
Description
"Partitions" or splits an array into two based on the predicate
. If predicate
returns true
, the item goes into list 1. Otherwise the item goes into list 2.
Implementation
const partition = (predicate, array) => array.reduce( (result, item) => { const [list1, list2] = result; if (predicate(item) === true) { list1.push(item); } else { list2.push(item); } return result; }, [[], []] );
Usage
const isEven = (x) => x % 2 === 0; partition(isEven, [1, 2, 3]); // [[2], [1, 3]] partition(isEven, [1, 3, 5]); // [[], [1, 3, 5]] partition(equals3, [1, 2, 3, 4, 3]); // [[3, 3], [1, 2, 4]] partition(equals3, [1, 2, 4]); // [[], [1, 2, 4]]
9. pluck
Parameters
key
- Key name to pluck from the objectarray
- List of items.
Description
Plucks the given key
off of each item in the array. Returns a new array of these values.
Implementation
const pluck = (key, array) => array.reduce((values, current) => { values.push(current[key]); return values; }, []);
Usage
pluck('name', [{ name: 'Batman' }, { name: 'Robin' }, { name: 'Joker' }]); // ['Batman', 'Robin', 'Joker'] pluck(0, [[1, 2, 3], [4, 5, 6], [7, 8, 9]]); // [1, 4, 7]
10. scan
Parameters
reducer
- Standard reducer function that receives two parameters - the accumulator and current element from the array.initialValue
- The initial value for the accumulator.array
- List of items.
Description
Ради исто као, reduce
али уместо само један резултат, он враћа листу свих смањених вредности на путу до појединачног резултата.
Имплементација
const scan = (reducer, initialValue, array) => { const reducedValues = []; array.reduce((acc, current) => { const newAcc = reducer(acc, current); reducedValues.push(newAcc); return newAcc; }, initialValue); return reducedValues; };
Употреба
const add = (x, y) => x + y; const multiply = (x, y) => x * y; scan(add, 0, [1, 2, 3, 4, 5, 6]); // [1, 3, 6, 10, 15, 21] - Every number added from 1-6 scan(multiply, 1, [1, 2, 3, 4, 5, 6]); // [1, 2, 6, 24, 120, 720] - Every number multiplied from 1-6
Желите бесплатан тренинг?
Ако желите да закажете бесплатан позив да бисте разговарали о фронт-енд развојним питањима у вези са кодом, интервјуима, каријером или нечим другим, пратите ме на Твиттер-у и ДМ-у.
Након тога, ако уживате у нашем првом састанку, можемо разговарати о континуираном подучавању које ће вам помоћи да постигнете своје фронт-енд развојне циљеве!
Хвала за читање
За више оваквог садржаја погледајте //иазеедб.цом!
До следећег пута!