Coder Social home page Coder Social logo

code_note's Introduction

Young Driver 🛴 💨 💨

I make simple tools to make developers' life easier

code_note's People

Contributors

littlee avatar

Stargazers

 avatar

Watchers

 avatar  avatar

code_note's Issues

React add temporary body class

componentDidMount:function(){
    var nClass = document.body.className + ' light';
    document.body.className = nClass.trim();
},

componentWillUnmount: function() {
    document.body.className = document.body.className.replace(/(?:^|\s)light(?!\S)/g, '');
},

React: render list in column

import React from 'react';
import { range } from 'lodash';

const Column = ReactComponent;
const ListItem = ReactComponent;

const renderListInColumn = (col, list) => {
  return range(col).map((n, i, arr) => (
    <Column key={i}>
      {list
        .filter((_, index) => index % arr.length === n)
        .map((item, index) => (
          <ListItem key={index} />
        ))}
    </Column>
  ));
};

Random Range Number

/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

/**
 * Returns a random integer between min (inclusive) and max (inclusive)
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Flat Tree (get all branches)

function getFlatTree(nodes) {
  var branch = []
  function dfs(nodes, pre) {
    nodes.forEach((node) => {
      if (node.children) {
        dfs(node.children, pre.concat({
          ...node,
          children: null
        }))
      }
      else {
        branch.push(pre.concat({
          ...node,
          children: null
        }))
      }
    })
  }
  dfs(nodes, [])
  return branch
}

NPM mirrors

electron_mirror=https://cdn.npm.taobao.org/dist/electron/
chromedriver_cdnurl=https://npm.taobao.org/mirrors/chromedriver
sass_binary_site=https://npm.taobao.org/mirrors/node-sass/
phantomjs_cdnurl=https://npm.taobao.org/mirrors/phantomjs
fse_binary_host_mirror=https://npm.taobao.org/mirrors/fsevents/
sharp_dist_base_url=https://npm.taobao.org/mirrors/sharp-libvips/v8.8.1/
canvas_binary_host_mirror=https://npm.taobao.org/mirrors/canvas-prebuilt/
PUPPETEER_DOWNLOAD_HOST=https://storage.googleapis.com.cnpmjs.org

Some git command

文件名乱码问题

git config --global core.quotepath fals

文件修改历史,仅显示文件名

git log --name-status --graph --oneline

create-react-app less support

{
  "scripts": {
    "start": "npm-run-all -p watch-less rs-start",
    "build": "npm-run-all -s build-less rs-build",
    "rs-build": "react-scripts build",
    "rs-start": "react-scripts start",
    "watch-less": "autoless ./src",
    "build-less": "autoless ./src --no-watch"
  }
}

grid layout position

function gridPosition({ length, width, height, cols }) {
  return Array(length)
    .fill('')
    .map((_, index) => {
      return {
        left: (index % cols) * width,
        top: Math.floor(index / cols) * height
      };
    });
}

vue `@` jsconfig.json

{
  "allowJs": true,
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Humanize Seconds

function humanizeSeconds(input, lang) {
  var dLang = lang || 'zh-cn'
  var secs = [24 * 60 * 60, 60 * 60, 60, 1]
  var f = [0, 0, 0, 0]
  var msg = {
    'zh-cn': ['秒', '分', '小时', '天'],
    'en': ['sec', 'min', 'hour', 'day']
  }

  if (!msg[dLang]) {
    dLang = 'zh-cn'
  }

  secs.forEach(function(item, index) {
    f[index] = Math.floor(input / item)
    input = input % item
  })

  f.reverse()
  var output = ''
  f.every(function(item, index) {
    if (item > 0) {
      output = ` ${item} ${msg[dLang][index]}` + output
      return true
    }
    return false
  })

  return output.trim()
}

wx.getLocalImgData dataUrl fixed

wx.getLocalImgData({
  localId: 'x',
  success: function(res) {
    var localData = res.localData;
    if (!/^data:image/.test(localData)) {
      localData = 'data:image/jgp;base64,' + localData;  // IT IS `jgp`, BUT WORKS
    }
    // your logic next
  }
});

make container can show all content with scale

const winW = window.innerWidth;
const winH = window.innerHeight;
const winRatio = winW / winH;
const triggerRatio = 750 / 1227;
if (winRatio > triggerRatio) {
  const scaleWidth = triggerRatio * winH;
  this.setState({
    scale: scaleWidth / winW
  });
}

url to blob with compression

export default function urlToBlob(url, compressWidth = 640, crossOrigin = false) {
  return new Promise((resolve, reject) => {
    let img = new Image();
    if (crossOrigin) {
      img.crossOrigin = "anonymous";
    }
    img.onload = () => {
      let canvas = document.createElement('canvas');
      let ratio = img.width / img.height;

      canvas.width = compressWidth;
      canvas.height = compressWidth / ratio;
      let ctx = canvas.getContext('2d');
      ctx.drawImage(
        img,
        0,
        0,
        img.width,
        img.height,
        0,
        0,
        canvas.width,
        canvas.height
      );
      canvas.toBlob(bin => {
        resolve(bin);
      });
    };
    img.onerror = () => {
      reject(img);
    }
    img.src = url;
  });
}

If ancient devices compatibility is required, add this polyfill for canvas.toBlob
https://github.com/blueimp/JavaScript-Canvas-to-Blob

shake event

    var threshold = 800
    var x = 0;
    var y = 0;
    var z = 0;
    var lastX = 0;
    var lastY = 0;
    var lastZ = 0;
    var lastTime = 0;

    window.addEventListener('devicemotion', function(e) {
      var g = e.accelerationIncludingGravity
      var now = new Date().getTime()

      if (now - lastTime > 100) {
        var diffTime = now - lastTime
        lastTime = now

        x = g.x
        y = g.y
        z = g.z

        var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000
        if (speed > threshold) {
          alert('shake')
        }
        lastX = x
        lastY = y
        lastZ = z
      }
    }, true)

Dispatch(func1, func2, func3...)

function cat() {
    var head = _.first(arguments)
    if (existy(head)) {
        return head.concat.apply(head, _.rest(arguments))
    }
    else {
        return []
    }
}

function construct(head, tail) {
    return cat([head], _.toArray(tail))
}

// An alternative to switch case >_< 
function dispatch(/* funcs */) {
    var funs = _.toArray(arguments)
    var size = funs.length

    return function(target /* , args */) {
        var ret = undefined
        var args = _.rest(arguments)

        for (var funIndex = 0; funIndex < size; funIndex++) {
            var fun = funs[funIndex]
            ret = fun.apply(fun, construct(target, args))

            if (existy(ret)) return ret
        }

        return ret
    }
}

Promisify

function promisify(fn) {
    return function() {
        var args = [].slice.call(arguments)
        return new Promise(function(resolve, reject) {
            fn.apply(null, args.concat(function(err, contents) {
                if (err) {
                    return reject(err)
                }
                resolve(contents)
            }))
        })
    }
}

var readFile = promisify(fs.readFile)
readFile('file.txt', 'utf-8').then(function(contents) {
    return 'something'
})

Pipeline

function pipeline(seed /*, args */) {
  return _.reduce(_.rest(arguments), function(l, r) {
    return r(l)
  }, seed)
}

webpack config for npm module

var path = require('path')

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    library: 'my-mod',
    libraryTarget: 'umd'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env', 'react']
          }
        }
      },
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader'}
        ]
      }
    ]
  },
  externals: {
    'react': 'react',
    'react-dom': 'react-dom'
  }
}

disable ios goBack cache

window.addEventListener('pageshow', function (e) {
  if (/(iPhone|iPad); /i.test(navigator.userAgent) && e.persisted) {
    window.location.reload();
  }
});

fabric.js useful options tricks

canvas:

new fabric.Canvas('canvas-id', {
  // ...
  enableRetinaScaling: false,
  selection: false,
  preserveObjectStacking: true
});

image:

new fabric.Image(img, {
  // ...
  selectable: false,
  evented: false
});

git rm sensitive file

git filter-branch --force --index-filter "git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" --prune-empty --tag-name-filter cat -- --all

iPhone Wechat Browser Size

Model With Nav No Nav
5(s/SE) 750 1066 750 1181
6/7/8(s) 750 1108 750 1206
6/7/8(s) Plus 750 1128 750 1217
XR 750 1313 750 1464
X(S) 750 1276 750 1448
XS Max 750 1313 750 1464

`[{ id, parentId}]` to nested `[{id, children}]`

2021 version

const listFromDb = [
  { id: 1 },
  { id: 2 },
  { id: 5, parentId: 4 },
  { id: 3, parentId: 1 },
  { id: 4, parentId: 2 }
];

function getChildrenTree(list) {
  const dataMap = list.reduce((acc, item) => {
    acc[item.id] = list.filter(({ parentId }) => parentId === item.id);
    return acc;
  }, {});

  function findChildren(arr) {
    return arr.map(item => {
      return {
        ...item,
        children: findChildren(dataMap[item.id])
      };
    });
  }

  return findChildren(list.filter(item => !item.parentId));
}

console.log(JSON.stringify(getChildrenTree(listFromDb), null, 2));

2016 version

function parentToChildren(data, idKey = 'id') {
  let dataMap = {};
  let list = data.slice();

  list.forEach((iItem, iIndex) => {
    dataMap[iItem[idKey]] = [];
    list.forEach((jItem, jIndex) => {
      if (iIndex !== jIndex && jItem.parent === iItem[idKey]) {
        dataMap[iItem[idKey]].push(list[jIndex]);
      }
    });
  });

  list.forEach((item, index) => {
    list[index].children = dataMap[list[index][idKey]];
  });

  list = list.filter(item => {
    return item.parent === null;
  });
  return list;
} 

Recursive Load Images

_loadImage = (e) => {
    this.setState((prevState) => {
      return {
        percent: prevState.percent + 1
      }
    })
    if (assets.length) {
      var img = new Image()
      img.onload = () => {
        setTimeout(
          this._loadImage,
          100 // 100ms delay
          )
      }
      img.src = assets.shift()
    }
    else {
      this.setState({
        page: PAGE_AFTER_IMG_LOADED
      })
    }
  }

assets is an array with image paths

Preview image before uploading

if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        $('#blah').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
}

gitignore Node x Windows x MacOS

build
node_modules

# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Dump file
*.stackdump

# Folder config file
[Dd]esktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# next.js build output
.next

Unregister Service Worker

navigator.serviceWorker.getRegistrations().then(function(registrations) {
  for (let registration of registrations) {
    registration.unregister();
  }
});

eslint-config wechat small app

module.exports = {
  env: {
    browser: true,
    commonjs: true,
    es6: true,
    node: true
  },
  extends: 'eslint:recommended',
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module'
  },
  rules: {
    indent: ['error', 2],
    'linebreak-style': ['error', 'unix'],
    quotes: ['error', 'single'],
    semi: ['error', 'always'],
    'no-console': ['off']
  },
  globals: {
    App: true,
    Page: true,
    getApp: true,
    wx: true,
    Component: true,
    getCurrentPages: true
  }
};

no adjacent duplicate random array, even end to end

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function rangeArr(min, max) {
  return new Array(max - min).fill(1).map((item, index) => min + item * index);
}

// 数组每一个元素不与自身前 diffLen 个元素重复,且最后一个元素不与整体前 diffLen 个元素重复
function noAdjDupRndArr(len, diffLen, min, max) {
  if (max - min < diffLen * 2) {
    throw Error('随机范围太小');
  }
  return new Array(len).fill('_').reduce((acc, _, index) => {
    const isLastDiff = index >= len - diffLen;
    const prev = acc
      .slice(-diffLen)
      .concat(isLastDiff ? acc.slice(0, diffLen - (len - 1 - index)) : []);
    const range = rangeArr(min, max).filter(item => {
      return prev.indexOf(item) === -1;
    });
    acc.push(range[randomInt(0, range.length - 1)]);
    return acc;
  }, []);
}

*uck float calculation

function floatToInt(num) {
  const arr = `${num}`.split('.');
  return {
    number: parseInt(arr.join('')),
    decLen: (arr[1] && arr[1].length) || 0
  };
}

function F(exp) {
  const match = exp.match(/^(\d+(?:\.\d+)?)\s*(\+|-|\*|\/)\s*(\d+(?:\.\d+)?)$/);
  if (!match) {
    throw Error(`floatCalc: "${exp}" is an invalid expression`);
  }
  const [numA, operation, numB] = match.slice(1);
  const intA = floatToInt(numA);
  const intB = floatToInt(numB);
  const maxDecLen = Math.max(intA.decLen, intB.decLen);
  const opA = intA.number * Math.pow(10, maxDecLen - intA.decLen);
  const opB = intB.number * Math.pow(10, maxDecLen - intB.decLen);
  switch (operation) {
    case '+': {
      return (opA + opB) / Math.pow(10, maxDecLen);
    }
    case '-': {
      return (opA - opB) / Math.pow(10, maxDecLen);
    }

    case '*': {
      return (opA * opB) / Math.pow(10, maxDecLen) / Math.pow(10, maxDecLen);
    }
    case '/': {
      return opA / opB / Math.pow(10, maxDecLen) / Math.pow(10, maxDecLen);
    }
    default:
  }
}

https

openssl req -newkey rsa:2048 -nodes -x509 -days 3650 -keyout key.pem -out cert.pem

remember to input common name

sublime text html snippet

file: fuck.sublime-snippet

<snippet>
  <content><![CDATA[
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>Title</title>
</head>
<body>
  
</body>
</html>
]]></content>
  <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
  <tabTrigger>fuck</tabTrigger>
  <!-- Optional: Set a scope to limit where the snippet will trigger -->
  <scope>text.html</scope>
</snippet>

throttle

function throttle( delay, callback ) {
  var last_exec = 0;
  return function() {
    var that = this,
    elapsed = new Date() - last_exec,
    args = arguments;

    if (elapsed > delay ) {
      last_exec = new Date();
      callback.apply( that, args );
    }
  }
}

SCSS function vw

@function vw($x, $vpw:750) {
  @return ($x / $vpw * 100) * 1vw;
}

translate px syntax to vw syntax
find: (\d+)px
replace: vw($1)

Existy and Truthy

function existy(x) {
    return x != null
}

function truthy(x) {
    return (x !== false) && existy(x)
}

hasClass, addClass, removeClass

function hasClass(el, className) {
  if (el.classList)
    return el.classList.contains(className)
  else
    return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
}

function addClass(el, className) {
  if (el.classList)
    el.classList.add(className)
  else if (!hasClass(el, className)) el.className += " " + className
}

function removeClass(el, className) {
  if (el.classList)
    el.classList.remove(className)
  else if (hasClass(el, className)) {
    var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
    el.className=el.className.replace(reg, ' ')
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.