对象 字符串 实用30-seconds-of-code

对象 字符串 实用30-seconds-of-code

原文:https://github.com/Chalarangelo/30-seconds-of-code

作者:Chalarangelo

翻译:http://caibaojian.com/30-seconds-of-code.html

译者:蔡宝坚

收集有用的 Javascript 片段, 你可以在30秒或更少的时间里理解。

cleanObj:移除从json对象指定的属性之外的任何特性

使用Object.keys()方法可以遍历给定的 json 对象并删除在给定数组中不是included 的键。另外, 如果给它一个特殊的键 (childIndicator), 它将在里面深入搜索, 并将函数应用于内部对象。

const cleanObj = (obj, keysToKeep = [], childIndicator) => {
Object.keys(obj).forEach(key => {
    if (key === childIndicator) {
    cleanObj(obj[key], keysToKeep, childIndicator);
    } else if (!keysToKeep.includes(key)) {
    delete obj[key];
    }
 })
}
/*
  const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
  cleanObj(testObj, ["a"],"children")
  console.log(testObj)// { a: 1, children : { a: 1}}
*/
objectFromPairs:从给定的键值对创建对象

使用Array.reduce()创建和组合键值对

const objectFromPairs = arr => arr.reduce((a,v)=>(a[v[0]]=v[1],a),{})
objectFromPairs([['a',1],['b',2]])
Object.entries()返回一个数组

其元素是与直接在object上找到的可枚举属性键值对相对应的数组。属性的顺序与通过手动循环对象的属性值所给出的顺序相同。

const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
objectToPairs:从对象创建键值对数组的数组

使用Object.keys()Array.map()循环访问对象的键并生成具有键值对的数组

const objectToPairs = obj => Object.keys(obj).map(item=>[item,obj[item]])
// objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])
shallowClone:创建对象的浅表克隆。

使用Object.assign()和一个空对象{}创建原始的浅克隆

const shallowClone = obj => Object.assign(obj,{})
/*
const a = { x: true, y: 1 };
const b = shallowClone(a);
a === b -> false
*/
truthCheckCollection:检查谓词 (第二个参数) 是否 truthy 集合的所有元素 (第一个参数)。

使用Array.every()检查每个传递的对象是否具有指定的属性, 以及是否返回 truthy 值。

truthCheckCollection = (collection, pre) => (collection.every(obj => obj[pre]));
// truthCheckCollection([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}], "sex") -> true

anagrams

生成字符串的所有字谜 (包含重复项)。

使用递归。对于给定字符串中的每个字母, 为其其余字母创建所有部分字谜。使用Array.map()将字母与每个部分变位词组合在一起, 然后将Array.reduce()组合在一个数组中的所有字谜。基本情况为字符串length等于21.

const anagrams = str => {
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str.split('').reduce((acc, letter, i) =>
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), []);
};
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
Capitalize:将字符串的第一个字母大写。

使用 destructuring 和toUpperCase()可将第一个字母、...rest用于获取第一个字母之后的字符数组, 然后是Array.join('')以使其成为字符串。省略lowerRest参数以保持字符串的其余部分不变, 或将其设置为true以转换为小写。

const Capitalize = ([first,...rest],lowerRest=false) => first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
// capitalize('myName') -> 'MyName'
// capitalize('myName', true) -> 'Myname'

capitalizeEveryWord

将字符串中每个单词的首字母大写。

使用replace()匹配每个单词和toUpperCase()的第一个字符以将其大写。

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
// capitalizeEveryWord('hello world!') -> 'Hello World!'

escapeRegExp

转义要在正则表达式中使用的字符串。

使用replace()可转义特殊字符。

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// escapeRegExp('(test)') -> \\(test\\)
reverseString:反转字符串。

使用数组 destructuring 和Array.reverse()可反转字符串中字符的顺序。使用join('')组合字符以获取字符串.

const reverseString = str => [...str].reverse().join('');
// reverseString('foobar') -> 'raboof'

truncateString

将字符串截断为指定长度。

确定字符串的length是否大于num。将截断的字符串返回到所需的长度, 并将...追加到末尾或原始字符串。

const truncateString = (str, num) =>
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
// truncateString('boomerang', 7) -> 'boom...'

实用

coalesce:返回第一个非空/未定义参数。

使用Array.find()返回第一个非null/undefined的参数find没找到的话返回undefined

const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_))
// coalesce(null,undefined,"",NaN, "Waldo") -> ""
coalesceFactory:返回自定义的联合函数, 返回从提供的参数验证函数返回true的第一个参数。

使用Array.find()返回从提供的参数验证函数返回true的第一个参数。

const coalesceFactory = valid => (...args) => args.find(valid);
// const customCoalesce = coalesceFactory(_ => ![null, undefined, "", NaN].includes(_))
// customCoalesce(undefined, null, NaN, "", "Waldo") //-> "Waldo"
isArray:检查给定参数是否为数组。

使用Array.isArray()检查某个值是否属于数组。

const isArray = val => !!val && Array.isArray(val);
// isArray(null) -> false
// isArray([1]) -> true
isBoolean:检查给定的参数是否为本机布尔元素。

使用typeof检查某个值是否被归类为布尔基元。

const isBoolean = val => typeof val === 'boolean';
// isBoolean(null) -> false
// isBoolean(false) -> true
isBoolean:检查给定的参数是否为本机布尔元素。

使用typeof检查某个值是否被归类为布尔基元。

const isBoolean = val => typeof val === 'boolean';
// isBoolean(null) -> false
// isBoolean(false) -> true

isFunction

检查给定参数是否为函数。

使用typeof检查某个值是否被归类为函数基元。

const isFunction = val => val && typeof val === 'function';
// isFunction('x') -> false
// isFunction(x => x) -> true

isNumber

检查给定参数是否为数字。

使用typeof检查某个值是否归类为数字基元。

const isNumber = val => typeof val === 'number';
// isNumber('1') -> false
// isNumber(1) -> true

isString

检查给定参数是否为字符串。

使用typeof检查某个值是否属于字符串基元。

const isString = val => typeof val === 'string';
// isString(10) -> false
// isString('10') -> true

isSymbol

检查给定参数是否为符号。

使用typeof检查某个值是否被归类为符号基元。

const isSymbol = val => typeof val === 'symbol';
// isSymbol('x') -> false
// isSymbol(Symbol('x')) -> true

timeTaken

测量执行函数所用的时间。

使用console.time()console.timeEnd()来测量开始和结束时间之间的差异, 以确定回调执行所用的时间。

const timeTaken = callback => {
console.time('timeTaken');  const r = callback();
console.timeEnd('timeTaken');  return r;
};
// timeTaken(() => Math.pow(2, 10)) -> 1024
// (logged): timeTaken: 0.02099609375ms

validateEmail

如果给定的字符串是有效的电子邮件, 则返回true, 否则为false

使用正则表达式检查电子邮件是否有效。如果电子邮件有效, 则返回 true, 如果没有, 则返回false

const validateEmail = str =>
  /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(str);
// validateEmail(mymail@gmail.com) -> true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 可以将 `date_history` 和 `data_history` 的创建合并成一行: ``` date_history, data_history = np.array(data.iloc[:, 0]), [x for item in np.array(data.iloc[:, 1]).tolist() for x in item] ``` 2. 可以在遍历 `date_history` 时,直接将字符串转为 datetime 对象,并添加到 `history_time_list` 中: ``` history_time_list = [datetime.datetime.strptime(date[0], '%Y/%m/%d %H:%M') for date in date_history] ``` 3. 在记录缺失位置时,可以用 `zip()` 函数将 `time_new_list` 和 `history_time_list` 同时遍历,这样会更加简洁: ``` code_list = [] for new_time, history_time in zip(time_new_list, history_time_list): while (new_time - history_time) != datetime.timedelta(minutes=0): history_time_list.insert(i, new_time) code_list.append(i) ``` 4. 可以使用 `pandas` 的 `interpolate()` 方法来进行缺失,这样可以省去很多代码: ``` data = data.set_index('date').resample('15T').interpolate().reset_index() ``` 综上所述,优化后的代码如下: ``` def data_processing(data): data.fillna(method='ffill', inplace=True) date_history, data_history = np.array(data.iloc[:, 0]), [x for item in np.array(data.iloc[:, 1]).tolist() for x in item] history_time_list = [datetime.datetime.strptime(date[0], '%Y/%m/%d %H:%M') for date in date_history] start_time, end_time, delta = history_time_list[0], history_time_list[-1], datetime.timedelta(minutes=15) time_new_list = [start_time + i * delta for i in range(int((end_time - start_time) / delta.total_seconds() / 60) + 1)] data = pd.DataFrame({'date': time_new_list, 'load': data_history}) data = data.set_index('date').resample('15T').interpolate().reset_index() return data ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值