DAY 8
0
Software Development

## review

1. 迭代(iterate) Array 中的每一個值
2. 轉換(transform) 其值
3. 建立(build) 新的 Array。

## overview

transduce :

``````const transduce = (transducer, reducer, initValue, collection) => {/** TODO */}
``````

into

``````const into = (to, transducer, from) => {/** TODO */}
``````

sequence

``````const sequence = (transducer, collection) => {/** TODO */}
``````

## rewrite transduce

``````const transduce = (transducer, reducer, initValue, collection) => {
let acc = initValue;

for (const val of collection) {
acc = transducer(reducer)(acc, val)
}

return acc;
}
``````

String

``````const toUpper = str => str.toUpperCase();
const isVowel = char => ['a', 'e', 'i', 'o', 'u'].includes(char.toLowerCase())

transduce(
compose(map(toUpper), filter(isVowel)),
(str, char) => str + char,
'',
'JingHuangSu',
) // IUAU

``````

Map

``````const tripleIt = (num) => num * 3;
const isEven = (num) => num % 2 === 0;

const numMap = new Map();
numMap.set('a', 1);
numMap.set('b', 2);
numMap.set('c', 3);
numMap.set('d', 4);

transduce(
compose(map(tripleIt), filter(isEven)),
(acc, val) => (acc.push(val), acc),
[],
numMap.values(),
); // [6, 12]
``````

Number (X)

*compose, filter, map 前篇自寫之函式

## into

``````const transduce = (transducer, reducer, initValue, _collection) => {
let acc = initValue;

const collection = R.is(Object, _collection) ? R.toPairs(_collection) : _collection;

for (const val of collection) {
acc = transducer(reducer)(acc, val)
}

return acc;
}
``````

``````const arrReducer = (acc, val) => (acc.push(val), acc)
const objectReducer = (obj, value) => Object.assign(obj, value);

const into = (to, transducer, from) => {
if (Array.isArray(to)) return transduce(transducer, arrReducer, to, collection);
else if (R.is(Object, to)) return transduce(transducer, objectReducer, to, collection);
throw new Error('into only supports arrays and objects as `to`');
};

into(
{},
{a: [1, 2, 3], b: [2, 3, 4]},
) // {a: [2, 3, 4], b: [3, 4, 5]}

``````

## sequence

sequence 則是更只需要輸入 transform 函式跟其要進行運算的資料結構就好!!

``````const sequence = (transducer, collection) => {
if (Array.isArray(collection)) return transduce(transducer, arrReducer, [], collection);
else if (R.is(Object, collection)) return transduce(transducer, objectReducer, {}, collection);
throw new Error('unsupported collection type!!!');
};

sequence(
{a: [1, 2, 3], b: [2, 3, 4]},
) // {a: [2, 3, 4], b: [3, 4, 5]}
``````

## 小結

NEXT: Type Signature