Transducers are composable algorithmic transformations. They are independent from the context of their input and output sources and specify only the essence of the transformation in terms of an individual element. Because transducers are decoupled from input or output sources, they can be used in many different processes - collections, streams, channels, observables, etc. Transducers compose directly, without awareness of input or creation of intermediate aggregates.

OK, short in description... let's see why we need it

  1. Normal Javascript `map`,`filter` create inter variable and loop though array everytime we call `map` or `filter` function, `transducer` can loop thought the array only ONCE and apply all the transofrmations necessary.
const data = [,,];
const inc = x => x + ;
const double = x => * x;
const lessThanThree = x => x < ;
////////////////////
/**
* Problem: We loop over array 3 times! We want to loop over only once
* in order to improve the profermance.
*/
const res1 = data
.filter(lessThanThree)
.map(double)
.map(inc) console.log(res1) // [3,5]

  2. We don't want to introduce any mutation or impure function such as `forEach` does, transducer are mutation free.

/**
* Problem: it is not pure function and we do mutation. But it is faster
* than we do .filter.map.map style, because it only loop the array once.
*/
let res2 = [];
data.forEach((x) => {
let item;
if (lessThanThree(x)) {
item = inc(double(x))
res2.push(item);
}
})
console.log(res2) // [3,5]

  3. We want to style functional style to keep the code more readable, in the meanwhile improve the proferemance:

/**
* Good: We avoid the mutation and can be write as pure function and it only loop once!
* Problem: But we lose our function composion style! We still want .filter.map.map styling.
* Meanwhile it should be profermance wise.
*/
const res3 = data.reduce((acc, curr) => {
if (lessThanThree(curr)) {
acc.push(inc(double(curr)));
}
return acc;
}, []);
console.log(res3); // [3,5]

OK, until now, we have some idea, what kind of code we want. Basiclly it should be composable and efficient.

The question is how to make composable code?

As we might know about, in OOP; if we want to chain multi function calls, from each function, we need to return `this`:

Class Bot {
...
sayName() {
console.log(this,name)
return this;
} sayHello() {
console.log("Hello")
return this;
} } const b = new Bot('Petter') b.sayName().sayHello()

For Array, the reason we can chain calls together is because each call return Array type. The same as String, number...

The key is we need to keep the input and output as the same type!

Therefore for function, we need to keep input function and output function have the same function signature!

//data.reduce(reducer, seed), reducer is something we can compose!
//Because reducer :: (acc, curr) => acc
//For every reducer functions' signature are the same.
//If the function sinature are the same, then we can compose function together!
const _mapReducer = (xf, array) =>
array.reduce((acc, curr) => {
acc.push(xf(curr))
return acc;
}, []);
const _filterReducer = (xf, array) =>
array.reduce((acc, curr) => {
if (xf(curr)) acc.push(curr);
return acc;
}, []);
// To make fns easy to compose, we extract 'array' data & init value
const mapReducer = (xf) => ((acc, curr) => {
acc.push(xf(curr))
return acc;
});
const filterReducer = pred => ((acc, curr) => {
if (pred(curr)) acc.push(curr);
return acc;
});
// now mapReducer and filterReducer both have the same function signature.
console.log(data.reduce(mapReducer(double), [])); // [2,4,6]
console.log(data.reduce(mapReducer(inc), [])); // [2,3,4]
console.log(data.reduce(filterReducer(lessThanThree), [])); // [1,2]
In order to compose reudcers together we need to make mapReducer and filterReducer as high order functions to take reducer as arguement, take a reducer as input and return a reducer signature as output is the key to do composion!
// In order to compose reudcers together we need to make mapReducer and filterReducer as high order functions to take reducer as arguement
// Take a reducer as input and return a reducer signature as output is the key to do composion!
const map = xf => reducer => ((acc, curr) => {
acc = reducer(acc, xf(curr))
return acc;
});
const filter = pred => reducer => ((acc, curr)=> {
if (pred(curr)) acc = reducer(acc, curr)
return acc;
})
// For mapReducer and filterReducer, we both do acc.push()
// therefore we can extrat this as base reducer
const pushReducer = (acc, value) => {
acc.push(value);
return acc;
};
Now we are able to use functional style and loop the array only once!
const doulbeLessThanThree = compose(
map(inc),
map(double),
filter(lessThanThree)
)
const res5 = data.reduce(doulbeLessThanThree(pushReducer), []);
console.log(res5); // [3,5]

Define our transducer!

/**
* transducer :: ((a -> b -> a), (a -> b -> a), [a], [a]) -> [a]
* @param {*} xf: base reducer
* @param {*} reducer: the composion redcuer signature
* @param {*} seed : init value
* @param {*} collection : data
*/
const transducer = (xf, reducer, seed, collection) => {
return collection.reduce(reducer(xf), seed);
}
const res6 = transducer(pushReducer, doulbeLessThanThree, [], data);
console.log(res6); // [3,5]

[Transducer] Step by Step to build a simple transducer的更多相关文章

  1. Build step 'Execute shell' marked build as failure解决

    今天jenkins构建时运行脚本报错如下: Build step 'Execute shell' marked build as failure 脚本没问题后来看了下原因是磁盘空间不足导致报错,清除下 ...

  2. Jenkins Build step 'Execute shell' marked build as failure

    问题出现: Jenkins一直都构建成功,今天突然报错:Jenkins Build step 'Execute shell' marked build as failure 问题原因: By defa ...

  3. [转]Bootstrap 3.0.0 with ASP.NET Web Forms – Step by Step – Without NuGet Package

    本文转自:http://www.mytecbits.com/microsoft/dot-net/bootstrap-3-0-0-with-asp-net-web-forms In my earlier ...

  4. Tomcat Clustering - A Step By Step Guide --转载

    Tomcat Clustering - A Step By Step Guide Apache Tomcat is a great performer on its own, but if you'r ...

  5. Code Understanding Step by Step - We Need a Task

      Code understanding is a task we are always doing, though we are not even aware that we're doing it ...

  6. 课程四(Convolutional Neural Networks),第一周(Foundations of Convolutional Neural Networks) —— 2.Programming assignments:Convolutional Model: step by step

    Convolutional Neural Networks: Step by Step Welcome to Course 4's first assignment! In this assignme ...

  7. Convolutional Neural Networks: Step by Step

    Andrew Ng deeplearning courese-4:Convolutional Neural Network Convolutional Neural Networks: Step by ...

  8. Sequence Models Week 1 Building a recurrent neural network - step by step

    Building your Recurrent Neural Network - Step by Step Welcome to Course 5's first assignment! In thi ...

  9. Step by step Process of creating APD

    Step by step Process of creating APD: Business Scenario: Here we are going to create an APD on top o ...

随机推荐

  1. Python并发编程-管道

    管道的作用- 两个进程间传递消息 from multiprocessing import Pipe, Process def func(conn1,conn2): conn2.close() #子进程 ...

  2. 2017/11/22 Leetcode 日记

    2017/11/22 Leetcode 日记 136. Single Number Given an array of integers, every element appears twice ex ...

  3. NOIP2017 D1T2时间复杂度

    这道题在考试时看到感觉与第一题放反了位置(因为我还没有看到第一题是结论题) 对于每个语句进行栈的模拟,而如果有语法错误就特判. 对于每一条for语句我们将其与栈顶元素连边,复杂度是1的我们不用考虑,如 ...

  4. 「BZOJ 2534」 L - gap字符串

    「BZOJ 2534」 L - gap字符串 题目描述 有一种形如 \(uv u\) 形式的字符串,其中 \(u\) 是非空字符串,且 \(v\) 的长度正好为 \(L\), 那么称这个字符串为 \( ...

  5. SpringBoot静态资源访问+拦截器+Thymeleaf模板引擎实现简单登陆

    在此记录一下这十几天的学习情况,卡在模板引擎这里已经是四天了. 对Springboot的配置有一个比较深刻的认识,在此和大家分享一下初学者入门Spring Boot的注意事项,如果是初学SpringB ...

  6. 清北学堂学习总结 day2 字符串 练习

    1.hash表(哈希表) codevs 2147 数星星--简单哈希  时间限制: 3 s  空间限制: 64000 KB  题目等级 : 钻石 Diamond 题目描述 Description 小明 ...

  7. ExifInterface针对照片的使用

    ExifInterface是保存照片信息的,那么我们在有需要的时候就可以通过这类,来获取照片的一些数码参数来做适当来逻辑处理,比较典型的案例就是android有的机型拍照或者选择照片后,照片可能会被旋 ...

  8. Vue学习记录-初探Vue

    写在开头 2017年,部门项目太多,而且出现了一个现象,即:希望既要有APP,也能够直接扫码使用,也能放到微信公众号里面. 从技术角度来说,APP我们可以选择原生开发,也可以选择ReactNative ...

  9. jpush-react-native 推送功能(Android 篇)

    github原地址 极光推送官方支持的 React Native 插件 安装 npm install jpush-react-native --savenpm install jcore-react- ...

  10. CentOS下使用KVM克隆虚拟机自动修改网卡的MAC地址

    克隆完虚拟机之后Mac地址还保留着母机的配置,此时需要修改成新的Mac地址才能继续,网上一般都是这样的手动操作: 参考:http://blog.51cto.com/freedyong/1361907 ...