TypeScript
by Terrance Smith
HTML
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
text-align: center;
}
TypeScript
class ArrayHelper{
static removeAtIndex<T>(arr:T[], index: number) {
const result = arr.splice(index, 1);
if (result.length !== 1) return null;
return result[0];
}
static insertAtIndex<T>(arr:T[], elem: T, index: number): T[] {
return [...arr.slice(0, index), elem, ...arr.slice(index)];
}
static insertBefore<T>(arr:T[], elem: T, predicate: (val: T) => boolean): T[] {
const index = arr.findIndex(predicate);
console.log('insertBefore index = '+index)
if (index === -1) return arr;
return arr.insertAtIndex(elem, index - 1);
}
static insertAfter<T>(arr:T[], elem: T, predicate: (val: T) => boolean): T[] {
const index = arr.findIndex(predicate);
if (index === -1) return arr;
return arr.insertAtIndex(elem, index);
}
}
const is1 = (i: number) => i===1;
const is4 = (i: number) => i===4;
const insertTest = [1,2,3,4];
const insertBeforeResult = ArrayHelper.insertBefore( insertTest, 10, is1);
const insertAtResult = ArrayHelper.insertAtIndex( insertTest, 5, 4);
const insertAfterResult = ArrayHelper.insertAfter( insertTest, 11, is4);
console.log('insertBeforeResult =' + insertBeforeResult);
console.log('insertAtResult ='+insertAtResult);
console.log('insertAfterResult =' + insertAfterResult);
//const before = [1,2,4].insertBefore(3,(i)=>i===4);
//const after = [1,2,3].insertAfter(4,(i)=>i===3);
//console.dir(`before = ${before}`);
//console.dir(`after = ${after}`);