コードスニペット集

よく使うけどなんだかんだ毎回調べているコードのスニペットについてまとめています。このてのスニペットには複数の選択肢があるので、個人的にベストプラクティスだと思うものをピックアップして記載しています。よりよいプラクティスがあればご連絡お願いします

# javascripts

Loop Key with Value of Object
for (let [key, value] of Object.entries(obj)) {
  ...
}
access nested object key without catching the ReferenceError that intermediate key is undefined

This snippet use loadash.get function.

const _ = require('lodash');

const nested = {
  'a': 1,
  'b': {
    'c': 2,
    'd': [3, 4 ,5]
  },
};

console.log(_.get(nested, 'a'));
// => 1
console.log(_.get(nested, 'b.d[1]'));
// => 4
console.log(_.get(nested, 'e.f.g'));
// => undefined (not ReferenceError: e is not defined)
console.log(_.get(nested, 'e.f.g', 'default'));
// => with default value
checks if values is an empty object, array, collection, or set.

This snippet use lodash.#isEmpty function.

const _ = require('lodash');                                                                                                                                                                                                              console.log(_.isEmpty({}));
// => true
console.log(_.isEmpty([]));
// => true
console.log(_.isEmpty(undefined));
// => true
console.log(_.isEmpty(null));                                                                                        // => true
console.log(_.isEmpty(''));
// => true
console.log(_.isEmpty(0));
// => true

::: moment with time-zone This snippet use moment-timezone npm module.

const moment = require('moment');
const momentTimezone = require('moment-timezone');

// UTC
console.log(moment().format('YYYY-MM-DD HH:mm'));
//=>  2021-02-16 01:49

// JST
console.log(momentTimezone().tz('Asia/Tokyo').format('YYYY-MM-DD HH:mm'));
//=> 2021-02-16 10:49

# One-Liner

Rscript
# percentile
$ seq 1 10 | docker run --rm -i r-base Rscript -e 'round(quantile (as.numeric (readLines ("stdin")), c(.80, .90, .99)), 2)' -
 80%  90%  99%
8.20 9.10 9.91

# summary
$ seq 1 10 | docker run --rm -i r-base Rscript -e 'round(summary (as.numeric (readLines ("stdin"))), 1)' -
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
    1.0     3.2     5.5     5.5     7.8    10.0

# standard deviation
$ seq 1 10 | docker run --rm -i r-base Rscript -e 'round(sd (as.numeric (readLines ("stdin"))), 4)' -
[1] 3.0277

# Linux

tail and head

tail -n, --lines=K

print the starting with the K(spcifed)th lines

$ tail -n +2 1-10.txt
2
3
4
5
6
7
8
9
10

tail -n, --lines=-K

print the last K(specified) lines

$ tail -n -2 1-10.txt
9
10

head -n, --lines=K

print the first K(specified) lines

$ head -n +2 1-10.txt
1
2

head -n, --lines=-K

print all but the last K(specified) lines of each file

$ head -n -2 1-10.txt
1
2
3
4
5
6
7
8

combined. last 5 lines of the files excludes header(first line)

$ tail -n +2 1-10.txt  | head -n 5
2
3
4
5
6
get pid from process name
$ pidof dockerd
Last Updated: 2021/4/9 17:01:46