Last active
July 2, 2018 10:13
-
-
Save codecakes/a4394cdcecf6b11492e4f06e6b171f53 to your computer and use it in GitHub Desktop.
typescript shuffling an array using new constructor classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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