5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【ネタ】JavaScript(とTypeScript)でSleep Sort

Last updated at Posted at 2017-04-24

カバーです。あくまでネタです。

var data = [5, 3, 6, 3, 6, 3, 1, 4, 7];

var sleepSort = function(arr){
    return new Promise(function(resolve,reject){
        var result = [];
        arr.forEach(function(d){
            setTimeout(function(){
                result.push(d);
                if(result.length === data.length) resolve(result);
            },d);
        });
    });
}

sleepSort(data).then(function(d){console.log(d)});
// [1, 3, 3, 3, 4, 5, 6, 6, 7]

...だからネタだってば。


追記。やっぱ素のJSだと気持ち悪いので一応TypeScriptでも書いておく。
コンパイル結果はほぼ同一だけど、慣れてしまうとこっちの方が書いてて安心感ある。


let data: number[] = [5, 3, 6, 3, 6, 3, 1, 4, 7];

let sleepSort = (arr: number[]) =>
    new Promise( (resolve, reject) => {
        let result: number[] = [];
        arr.forEach( (d: number) => {
            setTimeout( () => {
                result.push(d);
                if(result.length === data.length) resolve(result);
            },d);
        });
    });

sleepSort(data)
    .then((d) => console.log(d));

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?