Skip to content

Instantly share code, notes, and snippets.

@xialvjun
xialvjun / react-flyd-binding.js
Created Jul 21, 2016
Inspired by theadam/react-flyd. Allows for flyd streams to be embedded directly into JSX, and to update content when the streams fire events.
View react-flyd-binding.js
import { Component, createElement, cloneElement, isValidElement } from 'react'
import { isStream, on, combine } from 'flyd'
export function reactive(tag='') {
class ReactiveClass extends Component {
constructor(props) {
super(props)
this.displayName = `ReactiveClass-${typeof tag==='string' ? tag : (tag.displayName || tag.name || '')}`;
this.state = {}
}
@xialvjun
xialvjun / cache-react-component.js
Created Aug 9, 2016
Wrap a component class and get the CachedComponent. This CachedComponent will calculate a key from props and use the key to decide whether to construct a new instance and cache the old or recover the old component from cache and update props. We can use it with react-router easily to save up the time of constructing the RouteComponent you alread…
View cache-react-component.js
import React from 'react'
export default function cache(mapPropsToKey, option) {
mapPropsToKey = mapPropsToKey || (() => 'NoCache')
option = option || {}
// 默认最高5层,1000年
const {
count=5,
expire=3153600000000,
@xialvjun
xialvjun / Promise.some.js
Created Oct 25, 2016
Like Array.some and on the contrast of Promise.race, there is a Promise.some
View Promise.some.js
function some_sync(...ps) {
return (async () => {
let errors = []
while (true) {
try {
return await ps[errors.length]
} catch (error) {
errors.push(error)
if (errors.length === ps.length) {
throw errors
@xialvjun
xialvjun / koa-dataloader.js
Last active Dec 5, 2017
just a sample to show how to implement a js dataloader like facebook/dataloader
View koa-dataloader.js
const DataLoader = require('dataloader');
const { knex } = require('./singleton.js');
function middleware(ctx, next) {
const target = {};
const handler = {
get: function (receiver, table_name$key_column_name$) {
if (receiver[table_name$key_column_name$]) {
return receiver[table_name$key_column_name$];
@xialvjun
xialvjun / StackRoutes.jsx
Last active Jan 3, 2018
StackRoutes, make the router stacks like the modal, just agree with the history.
View StackRoutes.jsx
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Switch, Route, Link, withRouter, matchPath } from 'react-router-dom';
const db = {
authors: [
{ id: '8', name: 'xialvjun', gender: 'M', },
{ id: '1', name: 'lilei', gender: 'M' },
{ id: '7', name: 'hanmeimei', gender: 'F' },
@xialvjun
xialvjun / safe_add.js
Last active Jan 4, 2018
javascript safe add two float without worrying about float precision
View safe_add.js
// 其实这并不 safe。。。因为 js 中所有的数字其实都是浮点数,哪怕整数也是浮点数。。。
// 数值比较小的整数可能看不出来浮点数的特性,但是当数值比较大时,就能看出来了
// 还是直接用库来的方便实在:https://github.com/defunctzombie/num
function safe_add(a, b) {
const decimal_length = Math.max(...[a, b].map(n => (n + '').split('.')).map(n => (n[1] || '').length));
const power = Math.pow(10, decimal_length);
// 不要把 a*power+b*power 变为 (a+b)*power
return Math.round(a * power + b * power) / power;
}
View tree_table.js
import React, { Component } from 'react';
import { render } from 'react-dom';
var data = [
['1','1.1','1.1.1'],
['1','1.1','1.1.2'],
['1','1.1','1.1.3'],
['1','1.2','1.2.1'],
['1','1.2','1.2.2'],
['2','2.1','2.1.1', '2.1.1.1'],
View limit.js
// 返回一个可以任意执行,但内部并发只有 count 的函数
function limit(fn, count) {
let n = 0;
let ps = [];
function work(...args) {
n++;
let rp = fn(...args);
rp.then(_ => {
n--;
let next = ps.shift();// ps[0];
@xialvjun
xialvjun / easy_graphql_query_client.jsx
Created Apr 24, 2018
an naive version of react-apollo Query
View easy_graphql_query_client.jsx
import { createContext } from '@xialvjun/create-react-context';
import { create_client } from '@xialvjun/tiny-graphql-client';
import React, { Component } from 'react';
const tiny_client = create_client(async (body, extra_headers) => {
const res = await fetch('http://127.0.0.1:3000/graphql', {
method: 'post',
body: JSON.stringify(body),
headers: {
@xialvjun
xialvjun / react-inline-style.tsx
Created Jun 29, 2018
String inline style with prefix in React. DEPRECATED FOR `import {createInlineStyle} from '@xialvjun/create-react-style'`
View react-inline-style.tsx
import * as React from "react";
import { isValidElement } from "react";
import { createStyle } from "@xialvjun/create-react-style";
const StyleContext = createStyle();
function format_style(style) {
if (!style) {
return "";
}