Skip to content

Instantly share code, notes, and snippets.

@codecakes
Last active July 2, 2018 10:13
Show Gist options
  • Select an option

  • Save codecakes/a4394cdcecf6b11492e4f06e6b171f53 to your computer and use it in GitHub Desktop.

Select an option

Save codecakes/a4394cdcecf6b11492e4f06e6b171f53 to your computer and use it in GitHub Desktop.
typescript shuffling an array using new constructor classes
interface ContactInf {
name: string;
numbers: (number|string)[];
}
class Contact implements ContactInf {
constructor (public name: string, public numbers: (number|string)[]) {
console.info('creating');
};
// new es6 style
getName() {
this.name;
}
getNum() {
this.numbers;
}
};
// old style es5 way
// Contact.prototype.getName = ():string => this.name;
// Contact.prototype.getNum = ():string => this.numbers;
const
ar = ['a', 'b', 'c'],
d = [0, 1, 2, ...ar, 3, 4],
contact = new Contact('mat', d),
{name: matName, numbers: matNumbers} = contact,
ceilRandom = (ln: number, idx: number):number => {
return Math.floor((Math.random() * idx * 10)%ln);
},
shuffle = (arr: (number|string)[]) => {
let
ln:number = arr.length,
upper:number = 0;
for (let idx:number=0; idx < ln; idx++) {
upper = ceilRandom(ln, idx);
// console.info(`idx: ${idx}; upper: ${upper}; ln: ${ln}`);
let tmp = arr[upper];
arr[upper] = arr[idx];
arr[idx] = tmp;
// console.info(arr);
}
return arr;
};
console.info(shuffle(matNumbers));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment