Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cookbook 之 utils #22

Open
imyangyong opened this issue Aug 20, 2019 · 0 comments
Open

cookbook 之 utils #22

imyangyong opened this issue Aug 20, 2019 · 0 comments
Labels

Comments

@imyangyong
Copy link
Collaborator

imyangyong commented Aug 20, 2019

Input  TextArea 获取焦点时,将光标移至末尾
/**
   * method move cursor to end when focus. 
   * @param {Object} el target html dom.
   * @link https://davidwalsh.name/caret-end
   */
function moveCursorToEnd = el => {
    if (typeof el.selectionStart === 'number') {
      el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange !== 'undefined') {
      const range = el.createTextRange();
      range.collapse(false);
      range.select();
    }
  }
======
深拷贝(可用 lodash  _.cloneDeep 代替)
/**
   * method deep clone. 
   * @param {Object} source The object that will be cloned.
   */
function deepClone(source){
  if (!source) return source;
  if (source instanceof Date) return new Date(source);
  if (source instanceof RegExp) return new RegExp(source);
  if (typeof source !== 'object') return source;

  let newSource = new source.constructor();

  for(var key in source){
    newSource[key] = deepClone(source[key])
  }
  
  return newSource;
}
======
Object Keys 重命名
/**
   * method rename object keys. 
   * @param {Object} keysMap 新旧key对象形式的键值对.
   * @param {Object} obj 原始要改变的对象.
   */
const  renameKeys = (keysMap, obj) => Object
  .keys(obj)
  .reduce((acc, key) => ({
      ...acc,
      ...{ [keysMap[key] || key]: obj[key] }
  }), {});
// 应用示例:
keysMap = {
  name: 'firstName',
  job: 'passion'
};
obj = {
  name: 'YangYong',
  job: 'Front-End Master'
};
renameKeys(keysMap, obj);
// { firstName: 'YangYong', passion: 'Front-End Master' }
===
@imyangyong imyangyong changed the title utils cookbook cookbook 之 utils Aug 20, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant