Précédent   Forum des professionnels en informatique > Webmasters - Développement Web > Contribuez
Contribuez Proposez vos articles, cours, tutoriels, questions/réponses pour les FAQ, sources et autres ressources pour la rubrique Web ainsi que ses sous-rubriques.
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 05/02/2011, 22h27   #1
Expert Confirmé
 
Avatar de sekaijin
 
Femme
Urbaniste
Inscription : juillet 2004
Messages : 1 419
Détails du profil
Informations personnelles :
Sexe : Femme
Âge : 48
Localisation : France, Yvelines (Île de France)

Informations professionnelles :
Activité : Urbaniste
Secteur : Santé

Informations forums :
Inscription : juillet 2004
Messages : 1 419
Points : 2 806
Points : 2 806
Par défaut Quelques méthodes pour les tableaux

Bonjour
voici quelques méthodes pour travailler avec les tableaux

j'ai écris ça car j'ai constaté que souvent nous faisons re refaisons les même chose et souvent pas très bien entre autre j'ai par exemple trouvé dans code source ici même une parcours itératif pour déterminer si un élément fait partit d'un tableau alors que indexOf retourne -1 s'il n'y est pas

bref je ne dis pas que cet ensemble soit meilleur qu'un autre mais j'ai cherché à réunir les méthodes dont nous avons souvent besoin
méthode de classe
Code javascript :
1
2
3
4
5
//Class method check if argument is an array
//Array.isAn(aVar)
Array.isAn = function (b) {
  return Object.prototype.toString.call(b) == '[object Array]';
}
méthode ne modifiant pas l'objet
Code javascript :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//return true if argument is in this array
Array.prototype.isIn = function(a) {
  return -1 != this.indexOf(a)
}
 
//return new array has intersection of this and argument array
//throw exception if argument is not an array
Array.prototype.intersect = function(a) {
  var r = []
  if (!Array.isAn(a)) {
    throw a + ' is not an Array'
  }
  for(var i = 0, l = this.length; i < l; i++) {
    if ( -1 != a.indexOf(this[i])) && 
       ( -1 == r.indexOf(this[i])) {
        r.push(this[i])
    }
  }
  return r
}
 
//return new array has union of this and argument array
//throw exception if argument is not an array
Array.prototype.union = function(a) {
  var r = []
  if (!Array.isAn(a)) {
    throw a + ' is not an Array'
  }
  for(var i = 0, l = this.length; i < l; i++) {
    if ( -1 == r.indexOf(this[i])) {
      r.push(this[i])
    }
  }
  for(var i = 0, l = a.length; i < l; i++) {
    if ( -1 == r.indexOf(a[i])) {
      r.push(a[i])
    }
  }
  return r
}
 
//return new array containing all items
// of this not in argument array
//throw exception if argument is not an array
Array.prototype.minus = function(a) {
  var r = []
  if (!Array.isAn(a)) {
    throw a + ' is not an Array'
  }
  for(var i = 0, l = this.length; i < l; i++) {
    if ( -1 == a.indexOf(this[i])) {
      r.push(this[i])
    }
  }
  return r
}
 
//return new array containing all items
// of this not in argument array
// and all items of argument array not in this
//throw exception if argument is not an array
Array.prototype.diff = function(a) {
  if (!Array.isAn(a)) {
    throw a + ' is not an Array'
  }
  return this.minus(a).union(a.minus(this))
}
 
//return new array containing all result
// of argument function applied on all items
//throw exception if argument is not a function
Array.prototype.map = function(f) {
  var r = []
  if ( 'function' != typeof f) {
    throw f + ' is not a function'
  }
  for(var i = 0, l = a.length; i < l; i++) {  
    r.push(f(this[i]))
  }
  return r
}
 
//return new array containing all items
// for which the argument function returns true
//throw exception if argument is not a function
Array.prototype.filter = function(f) {
  var r = []
  if ( 'function' != typeof f) {
    throw f + ' is not a function'
  }
  for(var i = 0, l = a.length; i < l; i++) {
    if (f(this[i])) {
      r.push(this[i])
    }
  }
  return r
}
Méthodes modifiant l'objet
Code javascript :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//Append argument array to this
//throw exception if argument is not an array
Array.prototype.append = function (a) {
  if (!Array.isAn(a)) {
    throw a + ' is not an Array'
  }
  for(var i = 0, l = a.length; i < l; i++) {  
    this.push(a[i])
  }
  return this
}
 
//Pack delete all undéfined items
Array.prototype.pack = function() {
  //pack defined values
  for(var i = 0, j = 0, l = this.length; i < l; i++) {
    if ( 'undefined' == typeof this[i]) {
    } else if ( j == i) {
      j++
    } else {
      this[j] = this[i]
      j++
    }
  }
  //reduce array length
  for(var i = 0, l = this.length - j; i < l; i++) {
    this.pop()
  }
  return this
}
 
 
//remove all duplicate items of this
Array.prototype.clean = function() {
  //delete duplicate values
  for(var i = 0, l = this.length; i < l; i++) {
    if ( i != this.indexOf(this[i])) {
      delete (this[i])
    }
  }
  this.pack()
  return this
}
 
//delete an entry
Array.prototype.del = function(i) {
  //delete value
  if ( delete (this[i]) ) {
    this.pack()
  }
  return this
}
 
//remove all items of this that are in argument array
//throw exception if argument is not an array
Array.prototype.remove = function(a) {
  if (!Array.isAn(a)) {
    throw a + ' is not an Array'
  }
  for(var i = 0, l = this.length; i < l; i++) {
    if ( -1 != a.indexOf(this[i])) {
      delete(this[i])
    }
  }
  this.pack()
  return this
}
 
//remove all items for which the
// argument function returns true
//throw exception if argument is not a function
Array.prototype.wash = function(f) {
  if ( 'function' != typeof f) {
    throw f + ' is not a function'
  }
  for(var i = 0, l = a.length; i < l; i++) {
    if (f(this[i])) {
      delete(this[i])
    }
  }
  this.pack()
  return this
}
 
//apply argument function on all items
//throw exception if argument is not a function
Array.prototype.apply = function(f) {
  if ( 'function' != typeof f) {
    throw f + ' is not a function'
  }
  for(var i = 0, l = a.length; i < l; i++) {  
    this[i] = f(this[i])
  }
  return this
}
Gestion de piles
Code javascript :
1
2
3
4
5
6
7
8
//return the last item of this
//Array can be used has stack with push, pop and top méthods
Array.prototype.top = function () {
  if (0 == this.length) {
    throw 'Array is empty'
  }
  return this[this.length - 1];
}

Code javascript :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
a = [1,2,2]
b = [3,4]
c = [2, 3]
// a est un tableau ?
Array.isAn(a)
// 2 est-il dans a
a.isIn(2)
// 7 est-il dans a
a.isIn(7)
// nouveau tableau contenant les 
// éléments de c qui ne sont pas dans a
c.minus(a)
// nouveau tableau contenant les
// éléments de c qui ne sont pas dans b
c.minus(b)
// nouveau tableau contenant les
// éléments de a qui ne sont pas dans b
a.minus(b)
// nouveau tableau contenant les
// éléments de a et de b
a.union(b)
// nouveau tableau contenant les
// éléments qui sont dans a et b
a.intersect(c)
// nouveau tableau contenant les
// éléments de c qui ne sont pas dans a
// et de a qui ne sont pas dans c
c.diff(a)
// nouveau tableau contenant les
// résultats de la fonction sur chaque éléments de a
a.map(function(i){return (i + 6) % 2;})
// nouveau tableau contenant true ou false
// suivant le résultat de la fonc sur chaque éléments de a
a.filter(function(i){return i%2 == 0})
 
//ajoute à a les élément de b
a.append(b)
//élimine de a les doublons
a.clean()
 
//remplace chaque élément de a
// par le résultat de la fonction
a.apply(function(i){return (i + 6) % 2;})
//conserve dans a que les éléments
// pour lesquels la fonction vaut true
a.wash(function(i){return i%2 == 1})
 
//supprime de a l'élément d'index 1
a.del(1)
//supprime de a tous les éléments
// dont la valeur est dans le tableau
a.remove([1,3,5,7,9])
 
//consulte sans l'enlever le sommet de la pile a
a.top()

A+JYT
sekaijin est déconnecté   Envoyer un message privé Réponse avec citation 20
Vieux 21/07/2011, 11h12   #2
Expert Confirmé Sénior
 
Avatar de RomainVALERI
 
Homme Romain VALERI
POOête
Inscription : avril 2008
Messages : 2 572
Détails du profil
Informations personnelles :
Nom : Homme Romain VALERI
Âge : 35
Localisation : France, Meurthe et Moselle (Lorraine)

Informations professionnelles :
Activité : POOête

Informations forums :
Inscription : avril 2008
Messages : 2 572
Points : 4 073
Points : 4 073
Merci pour ces fonctions, je n'ai pas encore lu l'ensemble dans le détail mais ça me semble intéressant. ^^

Une question : ne voyant aucun ";" de fin d'instruction, et connaissant ta rigueur habituelle, je soupçonne une autre raison que la simple négligence... je me trompe ? Pourquoi les omettre ? la performance ?
__________________

...pour les linguistes et les curieux >>> générateur de phrases aléatoires

__________________
RomainVALERI est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 21/07/2011, 14h01   #3
Expert Confirmé
 
Avatar de sekaijin
 
Femme
Urbaniste
Inscription : juillet 2004
Messages : 1 419
Détails du profil
Informations personnelles :
Sexe : Femme
Âge : 48
Localisation : France, Yvelines (Île de France)

Informations professionnelles :
Activité : Urbaniste
Secteur : Santé

Informations forums :
Inscription : juillet 2004
Messages : 1 419
Points : 2 806
Points : 2 806
Ail

c'est ça de passer de langages en langages => un oubli

A+JYT
sekaijin est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 22/07/2011, 09h02   #4
Membre éclairé
 
Homme
F5(){F5}
Inscription : avril 2008
Messages : 256
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France, Rhône (Rhône Alpes)

Informations professionnelles :
Activité : F5(){F5}
Secteur : High Tech - Éditeur de logiciels

Informations forums :
Inscription : avril 2008
Messages : 256
Points : 320
Points : 320
salut,

Voici quelques propositions/remarques sur les méthodes ci-dessus :
Tout d'abord intersect : prendre le complémentaire de la différence
Code :
1
2
3
Array.prototype.intersect = function(a) {
  return this.union(a).minus(this.diff(a));
}
Dans l'union, tu check si ya pas de doublons à la place, on peut simplement supprimer les doublons après:
Code :
1
2
3
Array.prototype.union = function(a) {
  return this.concat(a).clean();
}
Dans le même genre d'idée pour minus
Code :
1
2
3
Array.prototype.minus = function(a) {
  return this.slice(0).remove(a);
}
map existe déjà (peut-être que quand tu l'as rédigée elle n'existait pas encore).
pour filter on peut combiner avec pack mais c'est vrai que la fonction fait plus que son but:
Code :
1
2
3
4
//f must returns undefined if it unvalidated this[i]; or identity otherwise
Array.prototype.filter = function(f) {
  return this.map(f).pack();
}
append c'est concat
top devrait plus s'appeler back, mais bon...

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
 
<html>
<script type="text/javascript">
function out(x){
 console.log(x);
}
Array.prototype.intersect = function(a) {
  return this.union(a).minus(this.diff(a));
}
 
Array.prototype.union = function(a) {
  return this.concat(a).clean();
}
 
Array.prototype.minus = function(a) {
  return this.slice(0).remove(a);
}
 
//f must returns false if it unvalidated this[i]; or identity otherwise
Array.prototype.filter = function(f) {
  return this.map(f).pack(false);
}
 
 
 
////////////////////COPY PASTED ////////////////////////////// 
 
//return new array containing all items
// of this not in argument array
// and all items of argument array not in this
//throw exception if argument is not an array
Array.prototype.diff = function(a) {
  if (!Array.isAn(a)) {
    throw a + ' is not an Array'
  }
  return this.minus(a).union(a.minus(this));
}
 
 
//return true if argument is in this array
Array.prototype.isIn = function(a) {
  return -1 != this.indexOf(a);
}
 
Array.isAn = function (b) {
  return Object.prototype.toString.call(b) == '[object Array]';
}
 
//Pack delete all undéfined items
Array.prototype.pack = function() {
  //pack defined values
  for(var i = 0, j = 0, l = this.length; i < l; i++) {
    if ( 'undefined' == typeof this[i]) {
    } else if ( j == i) {
      j++;
    } else {
      this[j] = this[i];
      j++;
    }
  }
  //reduce array length
  for(var i = 0, l = this.length - j; i < l; i++) {
    this.pop();
  }
  return this;
}
 
 
//remove all duplicate items of this
Array.prototype.clean = function() {
  //delete duplicate values
  for(var i = 0, l = this.length; i < l; i++) {
    if ( i != this.indexOf(this[i])) {
      delete (this[i]);
    }
  }
  this.pack();
  return this;
}
 
//remove all items of this that are in argument array
//throw exception if argument is not an array
Array.prototype.remove = function(a) {
  if (!Array.isAn(a)) {
    throw a + ' is not an Array';
  }
  for(var i = 0, l = this.length; i < l; i++) {
    if ( -1 != a.indexOf(this[i])) {
      delete(this[i]);
    }
  }
  this.pack();
  return this;
}
 
var a = [1,2,2];
var b = [3,4];
var c = [2, 3];
//----------------expected
out(c.minus(a));//3
out(c.minus(b));//2
out(a.minus(b));//1,2,2
out(a.union(b));//1,2,3,4
out(a.intersect(c));//2
out(c.diff(a));//1,3
out(a.map(function(i){return (i + 6) % 2;}));//1,0,0
out(a.filter(function(i){return (i%2 == 0)?undefined:i}));//1
out(a.clean());//1,2
 
 
</script>
</html>
galerien69 est déconnecté   Envoyer un message privé Réponse avec citation 10
Vieux 22/07/2011, 09h08   #5
Responsable JavaScript & AJAX

 
Avatar de vermine
 
Inscription : mars 2008
Messages : 2 686
Détails du profil
Informations personnelles :
Âge : 27

Informations forums :
Inscription : mars 2008
Messages : 2 686
Points : 5 768
Points : 5 768
Merci pour cette contribution et pour ces propositions/remarques.
__________________
Elen Poukram - Isegoria - Sandawe
vermine est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 08h38.


 
 
 
 
Partenaires

Hébergement Web