Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  93] [ 7]  / answers: 1 / hits: 52928  / 11 Years ago, mon, june 17, 2013, 12:00:00

Here is my code for javascript for this simple task:




  1. Remove the element if it exists in an array.

  2. Add the element if it is not in an array.



    if(_.contains(this.types,type_id)){
    var index = this.types.indexOf(type_id);
    this.types.splice(index,1);
    }
    else{
    this.types.push(type_id);
    }



Is there a more efficient way to do this?


More From » arrays

 Answers
14

If you care about efficiency then may be using an array to implement a set is a bad idea. For example using an object you could do:



function toggle(S, x) {
S[x] = 1 - (S[x]|0);
}


then after many add/remove operations you can keep only keys where the value is 1



This way every addition/removal is O(1) and you need only one O(n) operation to get the final result.



If keys are all small numbers may be a bitmask is even worth the effort (not tested)



function toggle(S, x) {
var i = x >> 4;
S[i] = (S[i]|0) ^ (1<<(x&15));
}

[#77581] Saturday, June 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
simone

Total Points: 558
Total Questions: 96
Total Answers: 99

Location: British Indian Ocean Territory
Member since Tue, Feb 22, 2022
2 Years ago
;