πΊπΈ Make an array method that can return whether or not a context array is a subset of an input array. To simplify the problem, you can assume that neither array will contain objects or arrays as elements within them.
Next level
: Make the method work for arrays that contain objects and/or arrays as elements.π¦π· Escriba una funcion que devuelva si cierto array dado es un subconjunto del array contextual. Para simplificar el problema, se puede suponer que ambos arrays no incluyen object/ array como elementos.
Proximo nivel
: reconstruye la funcion para que pueda aceptar object/ array.π°π· νΉμ λ°°μ΄ μ€ μ λ ₯ λ°°μ΄μ΄ νμ μ§ν©μΈμ§ μ¬λΆλ₯Ό λ°νν μ μλ ν¨μλ₯Ό λ§λμΈμ. λ¬Έμ λ₯Ό λ¨μννκΈ° μν΄ λ λ°°μ΄ λͺ¨λ κ°μ²΄ λλ λ°°μ΄λ₯Ό μμλ‘ ν¬ν¨νμ§ μλλ€.
λ€μ λ 벨
: κ°μ²΄ λ°/λλ λ°°μ΄μ μμλ‘ ν¬ν¨νλ μ
λ ₯ λ°°μ΄μ λν΄ λ©μλλ₯Ό 리νν λ§ νμΈμ.Example:
var a = ['commit','push']
a.isSubsetOf(['commit','rebase','push','blame']) // true
NOTE: You should disregard duplicates in the set.
var b = ['merge','reset','reset']
b.isSubsetOf(['reset','merge','add','commit']) // true
- See http://en.wikipedia.org/wiki/Subset for more on the definition of a
subset
.
Array.prototype.isSubsetOf = function(arr) {
// Your CODE
}
// Test
var a = ['commit','push']
a.isSubsetOf(['commit','rebase','push','blame'])
Solution π
.
.
.
.
.
.
.
.
.
.
.
.
.
.SOLUTION
Array.prototype.isSubsetOf = function(arr) {
// stringify all elements as obj's key
var obj = objectify(arr);
console.log(obj)
return this.reduce(function(acc, key) {
if (!obj[key]) {
return false;
}
return acc;
}, true);
function objectify(arr) {
var obj = {};
console.log(arr)
arr.forEach(function(key) {
obj[key] = 1; // if there is repeated [key] it overwrites
});
return obj;
}
}
// Test
var a = ['commit','push']
a.isSubsetOf(['commit','rebase','push','blame']) // true
// var b = ['merge','reset','reset']
// b.isSubsetOf(['reset','merge','add','commit']) // true
// var c = ['yum', 'meal']
// c.isSubsetOf(['poo', 'loo', 'yum'])
////// Extra Credit
// Test
var d = ['cool', ['beans'], {0: 'yum'}];
d.isSubsetOf([{0: 'yum'}, 'cool', 'cool', 'cool', ['beans'], 'dude'])
// var e = ['cool', ['beans'], {0: 'yum'}];
// e.isSubsetOf([{0: 'yum'}, 'dude', 'looks', 'like', 'a', 'lady'])