Skip to content

Instantly share code, notes, and snippets.

// 指定した条件の位置に値を追加する。合致しない場合は末尾に追加する。
Array.prototype.insertIf = function(value, condition) {
const index = this.findIndex(condition);
if (index < 0) {
this.push(value);
} else {
this.splice(index, 0, value);
}
return this;
}
// 複数行テキストの余分なインデントを除去する。
String.prototype.dedent = function() {
const lines = this.split("\n");
const indent = lines
.map(line => line.match(/^\s+(?=[^\s])/)?.[0].length)
.filter(n => n)
.reduce((a, b) => Math.min(a, b));
const re = new RegExp(`^\\s{${indent}}`);
return lines
.map(line => line.replace(re, ""))