Common Used Javascript Patterns for Screening Questions
· 約3分
短時間で、LeetCode問題を解決するスクリーニング面接はあります。 そのスクリーニング面接で使われている書き方は効率を重視し、代わりに、readability をTradeoffしても。 プロジェクトコーディングと全く別物で、よく使っているパターンをここでまとめます。
計算
Javascript において、除算は小数ついているため、整除ははMath.truncで、小数部分を切り捨てましょう。 また、Math.floor()は正数を正しく処理できますが、負数の処理は数学上の整除定義と異なるので、使わないでください。
Math.trunc(3 / 2) // → 1
Math.trunc(-3 / 2) // → -1
配列
配列の作成
const a = []; // empty
const b = [1,2,3]; // with elements
const c = new Array(n); // [ <n × empty> ]
const d = Array(n).fill(0); // [0,0,…,0]
const e = Array.from({ length: n }, (_, i) => i*2);
const f = [...someOtherArray]; // shallow copy
注意しなければないこと: 以下はReference作成で、おかしい挙動になります。
const d = Array(n).fill([]);
その他の配列の操作:
// find the index
["hello", "world"].indexOf("world")
// sort, O(nlgn)
arr.sort((a, b) => a - b);
// reverse in place
arr.reverse()
// non destructive subarray
arr.slice(start, end)
// unshift
// output: 5 length of new array
// array1 to be: [10, 11, 1, 2, 3]
const array1 = [1, 2, 3];
array1.unshift(10,11)
使ってはいけない操作:
shift
// shift
// remove the first element and returns that removed element
// However the time complexity is O(n), so
const array1 = [1,2,3];
while (firstElement = array1.shift()) {
// ❌
}
代わりに headを使って、先頭の位置だけメモし、Queueの操作を実現しましょう。
const array1 = [1,2,3];
const head = 0;
while (firstElement = array1[head++]) {
// ✅
}
文字列
charを取得
'abcde'.charAt(2); // 'c'