未加星标

Javascript needs a compose operator

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

javascript desperatly needs a compose operator. Borrowing from elixir, I propose the "|>" form. I'm open to outside suggestions. At its most basic, it would transpile down to an inline set of nested function calls.

the first argument would be passed into the function implictly and the rest in the parens would be partially applied after.

let output = a |> A(c) |> B(d); //let this transpile to let output = B(A(a, c), d);

This is a trivial example and you may be wondering if this is even worth the effort. I believe this simple abstraction would enable a level of api design that is currently impractical in today's javascript.

Obsoleting the chain pattern

Take lodash/underscore, if I want to map a set of numbers to their fibonaci versions and then filter all the even ones out, before I add them up, I could write it as follows.

let fn = (arr1) => { let arr2 = _.map(arr1, fib); let arr3 = _.filter(arr2, (x) => x % 2 !== 0); let arr4 = _.reduce(arr3, (val, memo) => memo + val, 0); return arr4; };

There'd alot of annoying lets in there. We can shorten it up using chain().

let fn = (arr1) => _.chain(arr1) .map(fib) .filter((x) => x % 2 !== 0) .reduce((val, memo) => memo + val, 0) .value()

Except it won't work. Reduce is not on the list of chainable functions in lodash. We'd have to end the chaining at filter and run the reduce seperatly.

import _ from 'lodash'; let fn = (arr1) => { let arr1 = _.chain(arr1) .map(fib) .filter((x) => x % 2 !== 0) .value(); return _.reduce(arr1, (val, memo) => memo + val, 0) }

The Chaining pattern is really a shitty workaround. It requires the api to pregroup functions that work together. Its really just a shitty substitute for the lack of a compose.

Instead, imagine if we had that compose operator. Reduce wouldn't have to be made to work with chain. We just need to make sure that the types being passed back and forth between the different functions are compatible.

Not only would it be cleaner but we can compose them seamlessly with our own functions that may not be part of lodash.

import {map, filter, reduce} from 'lodash'; let greaterThan = (x, 10) => x > 10; let add2 = (x) => x + 2; let fn = (arr) => arr |> map(fib) |> filter((x) => x % 2 !== 0) |> reduce((val, memo) => memo + val, 0); |> greaterThan(10) |> add2(); Moving towards functional Apis

The chain pattern is just the tip of the iceburg. What the chain pattern attempts to solve is the idea of a value being piped trhough various transformations before we get a final value. This appears all over the place in the javascript ecosystem but the chaining pattern results in an assortment of walled gardens requiring plugins to extend prototypes. This is alot of unecessary complexity.

Lets take the knexjs library. It uses a similar chaining pattern to build its queries.

//select the user record where id == 1 knex('users').where('id', 1); knex('users') .join('authorizations', 'users.id', 'authorizations.user_id') .where('users.id', 2)

Its clean and simple and for what it does, it works very well. The limitations come when you suddenly need to try somethign nonstandard.

Lets say we need to run a geolocation query. This is not supported out of the box in knex. Now our code becomes a combination of chaining patterns interpsersed with code that generates raw sql injected in using whereRaw();

let from_within(column, geom) = function() { ... } knex('users') .leftJoin('authorizations', 'users.id', 'authorizations.user_id') .where(from_within('authorizations.last_location', state));

I'm sure there's some way we could extend the prototype of knex to make this seamless. However it also just pushes back the original problem. We are coupling everythign to the internal state of the knex object and applying a bandage by adding methods.

I propose as an alternative, a shared data structure representing a query with a set of composable pure functions that operate on it.

Each function must return a new idempotent value that reflects the transformation. Perhaps immutable.js could be the base type. This frees us to write our own functions that assume simply have to take that data type, apply whatever transformations are needed and return a new copy.

As long as we follow the protocol, our in-house functions would compose jsut fine with the knex ones.

In theory, we could write the above logic as

import knex from 'knex'; let { select, fromTable, where, leftJoin } = knex.queryApi; let from_within(query, column, geom) = function() { ... }; //state represented with a geometry type let allLoginsInState = (state) => Knex.Query.create() |> fromTable('users') |> leftJoin('authorizations', 'users.id', 'authorizations.user_id') |> from_within('authorizations.last_location', state)

At this point, we can completely decouple the IO part from the query building to make unit testing much easier.

let { toSql } = knex.queryApi; let state = require('states.js').massachusetts; let expectedSql = "..."; expect(allLoginsInState(state) |> toSql()).to_eq() let state = require('states.js').massachusetts; (allLoginsInState(state) |> Knex.run()) .then(...) .catch(...);

Anyone else with me on this? Perhaps we can start with a Babel plugin.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: Java
分页:12
转载请注明
本文标题:Javascript needs a compose operator
本站链接:http://www.codesec.net/view/484282.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(31)