Modo entrevista. Temporizador de 10 min, sin pistas y sin autocompletado
Add, remove and sort Map entries
MediaMap and Set10 min
Write a function applyChanges(initial, toAdd, toRemove) that changes a map in three steps and returns its entries sorted by key.
initialandtoAddare arrays of pairs[key, value]. The key is a string, the value is a number. Keys insideinitialare unique, keys insidetoAddare unique too.toRemoveis an array of keys.- Step 1: create a
Mapfrominitial. - Step 2: add every pair of
toAdd. If the key is already in the map, it gets the new value. - Step 3: delete every key of
toRemovefrom the map. A key that is not in the map is ignored. - Return a new array of
[key, value]pairs, sorted by key. Compare keys as plain strings, the waysort()with no compare function orders strings: capital letters come before small letters, and a key comes before a longer key that starts with it. So'Banana'comes before'apple', and'item'comes before'item 2'. - Keys can contain capital letters and spaces. Any of the three arrays can be empty. If the map is empty at the end, return
[].
Ejemplos
applyChanges([['pear', 3], ['apple', 5]], [['kiwi', 2], ['apple', 7]], ['pear'])Devuelve [ [ 'apple', 7 ], [ 'kiwi', 2 ] ]
applyChanges([['cherry', 1], ['Banana', 2], ['apple', 3]], [], [])Devuelve [ [ 'Banana', 2 ], [ 'apple', 3 ], [ 'cherry', 1 ] ]
Preguntada en Accion Labs · Fuente
Cargando el editor…
- Entrada
applyChanges([ [ 'pear', 3 ], [ 'apple', 5 ] ], [ [ 'kiwi', 2 ] ], [ 'pear' ])Esperado[ [ 'apple', 5 ], [ 'kiwi', 2 ] ] - Entrada
applyChanges([ [ 'cherry', 1 ], [ 'banana', 2 ], [ 'apple', 3 ] ], [], [])Esperado[ [ 'apple', 3 ], [ 'banana', 2 ], [ 'cherry', 1 ] ] - Entrada
applyChanges([ [ 'apple', 5 ], [ 'pear', 1 ] ], [ [ 'apple', 7 ] ], [])Esperado[ [ 'apple', 7 ], [ 'pear', 1 ] ]
Las pruebas ocultas se ejecutan al enviar